diff --git a/doc/pub/week37/html/._week37-bs000.html b/doc/pub/week37/html/._week37-bs000.html index 39cfcfc18..541ecc814 100644 --- a/doc/pub/week37/html/._week37-bs000.html +++ b/doc/pub/week37/html/._week37-bs000.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -306,7 +273,7 @@ MathJax.Hub.Config({
-

September 9, 2024

+

September 8-12, 2025


@@ -333,7 +300,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • @@ -347,7 +314,7 @@ MathJax.Hub.Config({ -->
    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week37/html/._week37-bs001.html b/doc/pub/week37/html/._week37-bs001.html index 20713676b..3edf27444 100644 --- a/doc/pub/week37/html/._week37-bs001.html +++ b/doc/pub/week37/html/._week37-bs001.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -296,24 +263,18 @@ MathJax.Hub.Config({
    - -
  • Statistical interpretation of Ridge and Lasso regression, see also slides from last week
  • -
  • Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.
  • -
  • Readings and Videos:
  • - +

    The family of gradient descent methods

    +
      +
    1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge
    2. +
    3. Improving gradient descent with momentum
    4. +
    5. Introducing stochastic gradient descent
    6. +
    7. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM + +
    8. +
    -

    diff --git a/doc/pub/week37/html/._week37-bs002.html b/doc/pub/week37/html/._week37-bs002.html index abc8ee8ca..f673291cf 100644 --- a/doc/pub/week37/html/._week37-bs002.html +++ b/doc/pub/week37/html/._week37-bs002.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,22 +258,19 @@ MathJax.Hub.Config({

     

     

     

    -

    Plans for week 37, lab sessions

    - +

    Readings and Videos:

    - +
      +
    1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at https://www.deeplearningbook.org/contents/numerical.html and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html"
    2. +
    3. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
    4. +
    5. Video on gradient descent at https://www.youtube.com/watch?v=sDv4f4s2SB8
    6. +
    7. Video on Stochastic gradient descent at https://www.youtube.com/watch?v=vMh0zPT0tLI
    8. +
    - +

    @@ -325,7 +289,7 @@ MathJax.Hub.Config({

  • 11
  • 12
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs003.html b/doc/pub/week37/html/._week37-bs003.html index e4d022a2f..ccb14f2ac 100644 --- a/doc/pub/week37/html/._week37-bs003.html +++ b/doc/pub/week37/html/._week37-bs003.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,7 +258,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Material for lecture Monday September 9

    +

    Material for lecture Monday September 8

    @@ -311,7 +278,7 @@ MathJax.Hub.Config({

  • 12
  • 13
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs004.html b/doc/pub/week37/html/._week37-bs004.html index 439d8902b..5136d1a63 100644 --- a/doc/pub/week37/html/._week37-bs004.html +++ b/doc/pub/week37/html/._week37-bs004.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -290,26 +257,56 @@ MathJax.Hub.Config({

     

     

     

    - -

    Deriving OLS from a probability distribution

    + +

    Gradient descent and revisiting Ordinary Least Squares from last week

    -

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

    Last week we started with linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as:

    -

    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 -

    +
      +
    1. An analytical solution (recall homework sets for week 35).
    2. +
    3. The gradient can be computed analytically.
    4. +
    5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
    6. +
    +

    We revisit an example similar to what we had in the first homework set. We have a function of the type

    + + +
    +
    +
    +
    +
    +
    x = 2*np.random.rand(m,1)
    +y = 4+3*x+np.random.randn(m,1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    with \( x_i \in [0,1] \) is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +

    $$ -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]}. +h_\theta(x) = \boldsymbol{y} = \theta_0 + \theta_1 x, +$$ + +

    such that

    +$$ +\boldsymbol{y}_i = \theta_0 + \theta_1 x_i. $$ @@ -332,7 +329,7 @@ $$
  • 13
  • 14
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs005.html b/doc/pub/week37/html/._week37-bs005.html index 10778e05c..a2b3478ab 100644 --- a/doc/pub/week37/html/._week37-bs005.html +++ b/doc/pub/week37/html/._week37-bs005.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -290,39 +257,26 @@ MathJax.Hub.Config({

     

     

     

    - -

    Independent and Identically Distrubuted (iid)

    + +

    Gradient descent example

    -

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

    +

    Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\boldsymbol{y}} = (\boldsymbol{y}_1,\cdots,\boldsymbol{y}_n)^T \) and \( \theta = (\theta_0, \theta_1)^T \)

    + +

    It is convenient to write \( \mathbf{\boldsymbol{y}} = X\theta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by (we keep the intercept here)

    $$ -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]}, +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. $$ -

    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

    - +

    The cost/loss/risk function is given by (

    $$ -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}). +C(\theta) = \frac{1}{n}||X\theta-\mathbf{y}||_{2}^{2} = \frac{1}{n}\sum_{i=1}^{100}\left[ (\theta_0 + \theta_1 x_i)^2 - 2 y_i (\theta_0 + \theta_1 x_i) + y_i^2\right] $$ -

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

    +

    and we want to find \( \theta \) such that \( C(\theta) \) is minimized.

    @@ -344,7 +298,7 @@ $$

  • 14
  • 15
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs006.html b/doc/pub/week37/html/._week37-bs006.html index d4a52a9c3..f42693ebf 100644 --- a/doc/pub/week37/html/._week37-bs006.html +++ b/doc/pub/week37/html/._week37-bs006.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,32 +258,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Maximum Likelihood Estimation (MLE)

    +

    The derivative of the cost/loss function

    -

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

    +

    Computing \( \partial C(\theta) / \partial \theta_0 \) and \( \partial C(\theta) / \partial \theta_1 \) we can show that the gradient can be written as

    +$$ +\nabla_{\theta} C(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = \frac{2}{n}X^T(X\theta - \mathbf{y}), +$$ -

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

    +

    where \( X \) is the design matrix defined above.

    @@ -339,7 +290,7 @@ is equivalent to the maximization/minimization of the function itself.

  • 15
  • 16
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs007.html b/doc/pub/week37/html/._week37-bs007.html index 132b4b71c..71994bda6 100644 --- a/doc/pub/week37/html/._week37-bs007.html +++ b/doc/pub/week37/html/._week37-bs007.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,31 +258,16 @@ MathJax.Hub.Config({

     

     

     

    -

    A new Cost Function

    - -

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

    - +

    The Hessian matrix

    +

    The Hessian matrix of \( C(\theta) \) is given by

    $$ -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})}, +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X. $$ -

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

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    +

    This result implies that \( C(\theta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite.

    @@ -339,7 +291,7 @@ $$

  • 16
  • 17
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs008.html b/doc/pub/week37/html/._week37-bs008.html index b23162b7a..4cc405564 100644 --- a/doc/pub/week37/html/._week37-bs008.html +++ b/doc/pub/week37/html/._week37-bs008.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,42 +258,22 @@ MathJax.Hub.Config({

     

     

     

    -

    More basic Statistics and Bayes' theorem

    +

    Simple program

    -

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. +

    We can now write a program that minimizes \( C(\theta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to

    +$$ +\theta_{k+1} = \theta_k - \gamma \nabla_\theta C(\theta_k), \ k=0,1,\cdots +$$ + +

    We can use the expression we computed for the gradient and let use a +\( \theta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\theta C(\theta_k) || \leq \epsilon = 10^{-8} \). Note that the code below does not include the latter stop criterion.

    -

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    - -

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. -The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \). +

    And finally we can compare our solution for \( \theta \) with the analytic result given by +\( \theta= (X^TX)^{-1} X^T \mathbf{y} \).

    -
    -
    - -$$ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -$$ -
    -
    - - -
    -
    - -$$ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -$$ - -

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    -
    -
    - - -

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    -

    diff --git a/doc/pub/week37/html/._week37-bs009.html b/doc/pub/week37/html/._week37-bs009.html index 49d99d9b2..df9f8f43e 100644 --- a/doc/pub/week37/html/._week37-bs009.html +++ b/doc/pub/week37/html/._week37-bs009.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,16 +258,74 @@ MathJax.Hub.Config({

     

     

     

    -

    Marginal Probability

    +

    Gradient Descent Example

    -

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    -
    -
    - -$$ -p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). -$$ +

    Here our simple example

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +# Hessian matrix
    +H = (2.0/n)* X.T @ X
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y
    +print(theta_linreg)
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +for iter in range(Niterations):
    +    gradient = (2.0/n)*X.T @ (X @ theta-y)
    +    theta -= eta*gradient
    +
    +print(theta)
    +xnew = np.array([[0],[2]])
    +xbnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = xbnew.dot(theta)
    +ypredict2 = xbnew.dot(theta_linreg)
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    @@ -328,7 +353,7 @@ $$
  • 18
  • 19
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs010.html b/doc/pub/week37/html/._week37-bs010.html index d08fc5c74..075aea3b0 100644 --- a/doc/pub/week37/html/._week37-bs010.html +++ b/doc/pub/week37/html/._week37-bs010.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -290,18 +257,25 @@ MathJax.Hub.Config({

     

     

     

    - -

    Conditional Probability

    + +

    Gradient descent and Ridge

    -

    The conditional probability, if \( p(Y) > 0 \), is

    -
    -
    - +

    We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \theta \),

    $$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. +C_{\text{ridge}}(\theta) = \frac{1}{n}||X\theta -\mathbf{y}||^2 + \lambda ||\theta||^2, \ \lambda \geq 0. +$$ + +

    In order to minimize \( C_{\text{ridge}}(\theta) \) using GD we adjust the gradient as follows

    +$$ +\nabla_\theta C_{\text{ridge}}(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \theta_0 \\ \theta_1\end{bmatrix} = 2 (\frac{1}{n}X^T(X\theta - \mathbf{y})+\lambda \theta). +$$ + +

    We can easily extend our program to minimize \( C_{\text{ridge}}(\theta) \) using gradient descent and compare with the analytical solution given by

    +$$ +\theta_{\text{ridge}} = \left(X^T X + n\lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. $$ -
    -

    @@ -329,7 +303,7 @@ $$

  • 19
  • 20
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs011.html b/doc/pub/week37/html/._week37-bs011.html index e64c63365..87f9fdafa 100644 --- a/doc/pub/week37/html/._week37-bs011.html +++ b/doc/pub/week37/html/._week37-bs011.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,20 +258,21 @@ MathJax.Hub.Config({

     

     

     

    -

    Bayes' Theorem

    - -

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

    +

    The Hessian matrix for Ridge Regression

    +

    The Hessian matrix of Ridge Regression for our simple example is given by

    $$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X+2\lambda\boldsymbol{I}. $$ -

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

    +

    This implies that the Hessian matrix is positive definite, hence the stationary point is a +minimum. +Note that the Ridge cost function is convex being a sum of two convex +functions. Therefore, the stationary point is a global +minimum of this function. +

    @@ -331,7 +299,7 @@ $$

  • 20
  • 21
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs012.html b/doc/pub/week37/html/._week37-bs012.html index 4162a2125..90213a2d2 100644 --- a/doc/pub/week37/html/._week37-bs012.html +++ b/doc/pub/week37/html/._week37-bs012.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,17 +258,79 @@ MathJax.Hub.Config({

     

     

     

    -

    Interpretations of Bayes' Theorem

    +

    Program example for gradient descent with Ridge Regression

    -

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

    + +
    +
    +
    +
    +
    +
    from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
     
    -

    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.

    +# the number of datapoints +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X + +#Ridge parameter lambda +lmbda = 0.001 +Id = n*lmbda* np.eye(XT_X.shape[0]) + +# Hessian matrix +H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0]) +# Get the eigenvalues +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + + +theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y +print(theta_linreg) +# Start plain gradient descent +theta = np.random.randn(2,1) + +eta = 1.0/np.max(EigValues) +Niterations = 100 + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta + theta -= eta*gradients + +print(theta) +ypredict = X @ theta +ypredict2 = X @ theta_linreg +plt.plot(x, ypredict, "r-") +plt.plot(x, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Gradient descent example for Ridge') +plt.show() +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    Let us try to illustrate Bayes' theorem through an example.

    @@ -328,7 +357,7 @@ necesseraly normalized and is normally called the likelihood function.

  • 21
  • 22
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs013.html b/doc/pub/week37/html/._week37-bs013.html index 6df1dd439..0a3af037d 100644 --- a/doc/pub/week37/html/._week37-bs013.html +++ b/doc/pub/week37/html/._week37-bs013.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,28 +258,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Example of Usage of Bayes' theorem

    - -

    Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable \( X \). It takes binary -values with \( X=1 \) representing a positive event and \( X=0 \) being a -negative event. We reserve \( Y \) as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). -

    - -

    We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.

    - -

    Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have

    - -$$ -p(X=1\vert Y=1) =0.8. -$$ - -

    This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer. -It is however not correct, as the following Bayesian analysis shows. -

    +

    Using gradient descent methods, limitations

    +
      +
    • Gradient descent (GD) finds local minima of our function. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
    • +
    • GD is sensitive to initial conditions. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
    • +
    • Gradients are computationally expensive to calculate for large datasets. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, \( E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2 \); for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over all \( n \) data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called "mini batches". This has the added benefit of introducing stochasticity into our algorithm.
    • +
    • GD is very sensitive to choices of learning rates. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would adaptively choose the learning rates to match the landscape.
    • +
    • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
    • +
    • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
    • +

      @@ -338,7 +293,7 @@ It is however not correct, as the following Bayesian analysis shows.
    • 22
    • 23
    • ...
    • -
    • 54
    • +
    • 46
    • »
    diff --git a/doc/pub/week37/html/._week37-bs014.html b/doc/pub/week37/html/._week37-bs014.html index 434095bd7..2d1cd02f8 100644 --- a/doc/pub/week37/html/._week37-bs014.html +++ b/doc/pub/week37/html/._week37-bs014.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,28 +258,87 @@ MathJax.Hub.Config({

     

     

     

    -

    Doing it correctly

    +

    Improving gradient descent with momentum

    -

    If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is -

    +

    We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent.

    -$$ -p(Y=1) =0.004. -$$ -

    We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have

    -$$ -p(X=1\vert Y=0) =0.1. -$$ + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# take a step
    +		solution = solution - step_size * gradient
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# perform the gradient descent search
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute

    - -$$ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -$$ - -

    That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!

    @@ -339,7 +365,7 @@ $$

  • 23
  • 24
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs015.html b/doc/pub/week37/html/._week37-bs015.html index 3d2fc7b18..39be69329 100644 --- a/doc/pub/week37/html/._week37-bs015.html +++ b/doc/pub/week37/html/._week37-bs015.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,32 +258,93 @@ MathJax.Hub.Config({

     

     

     

    -

    Bayes' Theorem and Ridge and Lasso Regression

    +

    Same code but now with momentum gradient descent

    -

    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})], -$$ + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# keep track of the change
    +	change = 0.0
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# calculate update
    +		new_change = step_size * gradient + momentum * change
    +		# take a step
    +		solution = solution - new_change
    +		# save the change
    +		change = new_change
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# define momentum
    +momentum = 0.3
    +# perform the gradient descent search with momentum
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    @@ -343,7 +371,7 @@ $$

  • 24
  • 25
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs016.html b/doc/pub/week37/html/._week37-bs016.html index 968a2bd0c..1b3515b56 100644 --- a/doc/pub/week37/html/._week37-bs016.html +++ b/doc/pub/week37/html/._week37-bs016.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,41 +258,9 @@ MathJax.Hub.Config({

     

     

     

    -

    Ridge and Bayes

    +

    Overview video on Stochastic Gradient Descent

    -

    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?

    +What is Stochastic Gradient Descent

    @@ -352,7 +287,7 @@ $$

  • 25
  • 26
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs017.html b/doc/pub/week37/html/._week37-bs017.html index 85840d3d6..e1882aad3 100644 --- a/doc/pub/week37/html/._week37-bs017.html +++ b/doc/pub/week37/html/._week37-bs017.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,36 +258,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Lasso and Bayes

    +

    Batches and mini-batches

    -

    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

    +

    In gradient descent we compute the cost function and its gradient for all data points we have.

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

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update.

    -$$ -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/pub/week37/html/._week37-bs018.html b/doc/pub/week37/html/._week37-bs018.html index 984b49900..a4b654a0b 100644 --- a/doc/pub/week37/html/._week37-bs018.html +++ b/doc/pub/week37/html/._week37-bs018.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,17 +258,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Why resampling methods

    +

    Stochastic Gradient Descent (SGD)

    -

    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 +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set.

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

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    @@ -328,7 +309,7 @@ our regression analysis. In what follows we will

  • 27
  • 28
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs019.html b/doc/pub/week37/html/._week37-bs019.html index 8a1c65a3e..ceb6547d6 100644 --- a/doc/pub/week37/html/._week37-bs019.html +++ b/doc/pub/week37/html/._week37-bs019.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,32 +258,20 @@ MathJax.Hub.Config({

     

     

     

    -

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

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above.

    -

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

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \),

    -
    -
    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$

    @@ -344,7 +299,7 @@ cross-validation and the bootstrap method.

  • 28
  • 29
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs020.html b/doc/pub/week37/html/._week37-bs020.html index 6468726a1..75db11f4d 100644 --- a/doc/pub/week37/html/._week37-bs020.html +++ b/doc/pub/week37/html/._week37-bs020.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,30 +258,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling approaches can be computationally expensive

    -
    -
    - +

    Computation of gradients

    -

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

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients

    -
    -
    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    @@ -341,7 +300,7 @@ bootstrap is widely used.

  • 29
  • 30
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs021.html b/doc/pub/week37/html/._week37-bs021.html index 6e98db575..4a4d3fe14 100644 --- a/doc/pub/week37/html/._week37-bs021.html +++ b/doc/pub/week37/html/._week37-bs021.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,19 +258,28 @@ MathJax.Hub.Config({

     

     

     

    -

    Why resampling methods ?

    -
    -
    - +

    SGD example

    +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ -
      -
    • 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.
    • -
    -
    -
    -

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

  • 30
  • 31
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs022.html b/doc/pub/week37/html/._week37-bs022.html index 06e98daf2..2921b04c2 100644 --- a/doc/pub/week37/html/._week37-bs022.html +++ b/doc/pub/week37/html/._week37-bs022.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,23 +258,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Statistical analysis

    -
    -
    - +

    The gradient step

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

    Thus a gradient descent step now looks like

    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    @@ -334,7 +298,7 @@ MathJax.Hub.Config({

  • 31
  • 32
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs023.html b/doc/pub/week37/html/._week37-bs023.html index e93b245a9..c65574214 100644 --- a/doc/pub/week37/html/._week37-bs023.html +++ b/doc/pub/week37/html/._week37-bs023.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,29 +258,51 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling methods

    +

    Simple example code

    -

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

    + +
    +
    +
    +
    +
    +
    import numpy as np 
     
    -

    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. +n = 100 #100 datapoints +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +n_epochs = 10 #number of epochs + +j = 0 +for epoch in range(1,n_epochs+1): + for i in range(m): + k = np.random.randint(m) #Pick the k-th minibatch at random + #Compute the gradient using the data in minibatch Bk + #Compute new suggestion for + j += 1 +

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

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints.

    @@ -341,7 +330,7 @@ training error reaches a saturation.

  • 32
  • 33
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs024.html b/doc/pub/week37/html/._week37-bs024.html index 28c3a2321..90d0eed4e 100644 --- a/doc/pub/week37/html/._week37-bs024.html +++ b/doc/pub/week37/html/._week37-bs024.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,28 +258,19 @@ MathJax.Hub.Config({

     

     

     

    -

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

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value.

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

    @@ -339,7 +297,7 @@ advantages:

  • 33
  • 34
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs025.html b/doc/pub/week37/html/._week37-bs025.html index 6cf71a941..f248bb5e5 100644 --- a/doc/pub/week37/html/._week37-bs025.html +++ b/doc/pub/week37/html/._week37-bs025.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,24 +258,19 @@ MathJax.Hub.Config({

     

     

     

    -

    The Central Limit Theorem

    +

    Slightly different approach

    -

    Suppose we have a PDF \( p(x) \) from which we generate a series \( N \) -of averages \( \mathbb{E}[x_i] \). Each mean value \( \mathbb{E}[x_i] \) -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 \( \mathbb{E}[x_i]=x_i \) in the discussion -which follows. We do the same for \( \mathbb{E}[z]=z \). +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. Such approaches are +also called scaling. There are many such ways to scale the learning +rate +and discussions here. See +also +https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1 +for a discussion of different scaling functions for the learning rate.

    -

    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/pub/week37/html/._week37-bs026.html b/doc/pub/week37/html/._week37-bs026.html index dafed4d4a..af0e823ac 100644 --- a/doc/pub/week37/html/._week37-bs026.html +++ b/doc/pub/week37/html/._week37-bs026.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,24 +258,64 @@ MathJax.Hub.Config({

     

     

     

    -

    Finding the Limit

    +

    Time decay rate

    -

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

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    -

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

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function.

    + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

      @@ -334,7 +341,7 @@ product of individual \( p(x_i) \). The independence assumption is important in
    • 35
    • 36
    • ...
    • -
    • 54
    • +
    • 46
    • »
    diff --git a/doc/pub/week37/html/._week37-bs027.html b/doc/pub/week37/html/._week37-bs027.html index 1718f7fbc..e59a6392a 100644 --- a/doc/pub/week37/html/._week37-bs027.html +++ b/doc/pub/week37/html/._week37-bs027.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,31 +258,96 @@ MathJax.Hub.Config({

     

     

     

    -

    Rewriting the \( \delta \)-function

    +

    Code with a Number of Minibatches which varies

    -

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

    +

    In the code here we vary the number of mini-batches.

    -$$ - \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)}, -$$ + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
     
    -

    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, -$$ +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) -

    with the integral over \( x \) resulting in

    +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") -$$ - \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]. -$$ +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ ((X @ theta)-y) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 + +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    @@ -343,7 +375,7 @@ $$

  • 36
  • 37
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs028.html b/doc/pub/week37/html/._week37-bs028.html index b140d6739..abcec5972 100644 --- a/doc/pub/week37/html/._week37-bs028.html +++ b/doc/pub/week37/html/._week37-bs028.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,33 +258,12 @@ MathJax.Hub.Config({

     

     

     

    -

    Identifying Terms

    +

    Replace or not

    -

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

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful.

    @@ -345,7 +291,7 @@ and \( \mu \) is also the mean of the PDF \( p(x) \).

  • 37
  • 38
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs029.html b/doc/pub/week37/html/._week37-bs029.html index d5bb0afc5..e085e692b 100644 --- a/doc/pub/week37/html/._week37-bs029.html +++ b/doc/pub/week37/html/._week37-bs029.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,46 +258,39 @@ MathJax.Hub.Config({

     

     

     

    -

    Wrapping it up

    +

    Momentum based GD

    -

    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 central limit theorem leads to the well-known expression for the -standard deviation, given by +

    The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows

    $$ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\tag{1} +\end{align} $$ -

    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 (the so-called Bessel correction) -

    -$$ - \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. Keep -in mind that we have assumed that the variables \( x \) are independent -and identically distributed. This is obviously not always the -case. For example, the random numbers (or better pseudorandom numbers) -we generate in various calculations do always exhibit some -correlations. +

    where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is

    -

    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 form /analytic expression for -\( \tilde{p}(x) \). -

    +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    @@ -357,7 +317,7 @@ finite \( m \), it is not always possible to find a closed form /analytic expres

  • 38
  • 39
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs030.html b/doc/pub/week37/html/._week37-bs030.html index c0af19a83..e149be2ff 100644 --- a/doc/pub/week37/html/._week37-bs030.html +++ b/doc/pub/week37/html/._week37-bs030.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,24 +258,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Confidence Intervals

    +

    More on momentum based approaches

    -

    Confidence intervals are used in statistics and represent 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. +

    Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by

    -

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

    +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ -

    In the exercises this week we show 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} \). -

    +

    We can discretize this equation in the usual way to get

    + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

    Rearranging this equation, we can rewrite this as

    + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ -

    This quantity can be used to -construct a confidence interval for the estimates. -

    @@ -335,7 +309,7 @@ construct a confidence interval for the estimates.

  • 39
  • 40
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs031.html b/doc/pub/week37/html/._week37-bs031.html index c4b348795..1463b079c 100644 --- a/doc/pub/week37/html/._week37-bs031.html +++ b/doc/pub/week37/html/._week37-bs031.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,32 +258,58 @@ MathJax.Hub.Config({

     

     

     

    -

    Standard Approach based on the Normal Distribution

    +

    Momentum parameter

    -

    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 +

    Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as:

    $$ -\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. $$ -

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

    Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \).

    -

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

    Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models.

    +

    These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). +

    + +

    In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule +

    + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\tag{2} +\end{align} +$$ + +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    +

      @@ -342,7 +335,7 @@ Bootstrap method, why it works and various theorems related to it.
    • 40
    • 41
    • ...
    • -
    • 54
    • +
    • 46
    • »
    diff --git a/doc/pub/week37/html/._week37-bs032.html b/doc/pub/week37/html/._week37-bs032.html index abd32b421..21fd568cf 100644 --- a/doc/pub/week37/html/._week37-bs032.html +++ b/doc/pub/week37/html/._week37-bs032.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,17 +258,29 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling methods: Bootstrap background

    +

    Second moment of the gradient

    -

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

    In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. +

    + +

    Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and +ADAM.

    @@ -329,7 +308,7 @@ estimators.

  • 41
  • 42
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs033.html b/doc/pub/week37/html/._week37-bs033.html index cbea0e7d2..a375fe4c2 100644 --- a/doc/pub/week37/html/._week37-bs033.html +++ b/doc/pub/week37/html/._week37-bs033.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,22 +258,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling methods: More Bootstrap background

    +

    RMS prop

    -

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

    In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given 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}) \). + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

    where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions.

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

  • 42
  • 43
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs034.html b/doc/pub/week37/html/._week37-bs034.html index a867dfa1c..1d4ebc309 100644 --- a/doc/pub/week37/html/._week37-bs034.html +++ b/doc/pub/week37/html/._week37-bs034.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,21 +258,60 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling methods: Bootstrap approach

    +

    ADAM optimizer

    -

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

    A related algorithm is the ADAM optimizer. In +ADAM, we keep a running average of +both the first and second moment of the gradient and use this +information to adaptively change the learning rate for different +parameters. The method isefficient when working with large +problems involving lots data and/or parameters. It is a combination of the +gradient descent with momentum algorithm and the RMSprop algorithm +discussed above.

    -

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

    In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below)

    +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\tag{5} +\end{align} +$$ + +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    + +

    Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - +(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by +

    + +$$ +\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + +

      @@ -331,7 +337,7 @@ result in some asymptotic sense? The answer is yes.
    • 43
    • 44
    • ...
    • -
    • 54
    • +
    • 46
    • »
    diff --git a/doc/pub/week37/html/._week37-bs035.html b/doc/pub/week37/html/._week37-bs035.html index f843ffbc1..8d2b305ee 100644 --- a/doc/pub/week37/html/._week37-bs035.html +++ b/doc/pub/week37/html/._week37-bs035.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,26 +258,11 @@ MathJax.Hub.Config({

     

     

     

    -

    Resampling methods: Bootstrap steps

    +

    Algorithms and codes for Adagrad, RMSprop and Adam

    -

    The independent bootstrap works like this:

    +

    The algorithms we have implemented are well described in the text by Goodfellow, Bengio and Courville, chapter 8.

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

    +

    The codes which implement these algorithms are discussed below here.

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

  • 44
  • 45
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs036.html b/doc/pub/week37/html/._week37-bs036.html index f191c3bab..e3d652f14 100644 --- a/doc/pub/week37/html/._week37-bs036.html +++ b/doc/pub/week37/html/._week37-bs036.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,72 +258,14 @@ MathJax.Hub.Config({

     

     

     

    -

    Code example for the Bootstrap method

    - -

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

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from time import time
    -from scipy.stats import norm
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples 
    -# Bootstrap algorithm
    -def bootstrap(data, datapoints):
    -    t = np.zeros(datapoints)
    -    n = len(data)
    -    # non-parametric bootstrap         
    -    for i in range(datapoints):
    -        t[i] = np.mean(data[np.random.randint(0,n,n)])
    -    # analysis    
    -    print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))
    -    return t
    -
    -# We set the mean value to 100 and the standard deviation to 15
    -mu, sigma = 100, 15
    -datapoints = 10000
    -# We generate random numbers according to the normal distribution
    -x = mu + sigma*np.random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, datapoints)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

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

    +

    Practical tips

    +
      +
    • Randomize the data when making mini-batches. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
    • +
    • Transform your inputs. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
    • +
    • Monitor the out-of-sample performance. Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This early stopping significantly improves performance in many settings.
    • +
    • Adaptive optimization methods don't always have good generalization. Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
    • +

      @@ -381,8 +290,6 @@ t = bootstrap(x, datapoints)
    • 44
    • 45
    • 46
    • -
    • ...
    • -
    • 54
    • »
    diff --git a/doc/pub/week37/html/._week37-bs037.html b/doc/pub/week37/html/._week37-bs037.html index 510a4a4ba..32d254b75 100644 --- a/doc/pub/week37/html/._week37-bs037.html +++ b/doc/pub/week37/html/._week37-bs037.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,7 +258,12 @@ MathJax.Hub.Config({

     

     

     

    -

    Plotting the Histogram

    +

    Sneaking in automatic differentiation using Autograd

    + +

    We anticipate our discussions to come in connection with neural networks and automatic differentiation +by showing how we can use autograd for the cases above. Later we will replace autograd with JAX. +

    +
    @@ -299,14 +271,54 @@ MathJax.Hub.Config({
    -
    # the histogram of the bootstrapped data (normalized data if density = True)
    -n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)
    -# add a 'best fit' line  
    -y = norm.pdf(binsboot, np.mean(t), np.std(t))
    -lt = plt.plot(binsboot, y, 'b', linewidth=1)
    -plt.xlabel('x')
    -plt.ylabel('Probability')
    -plt.grid(True)
    +  
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
     plt.show()
     
    @@ -347,9 +359,6 @@ plt.show()
  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs038.html b/doc/pub/week37/html/._week37-bs038.html index 7825353e5..0d2d20f03 100644 --- a/doc/pub/week37/html/._week37-bs038.html +++ b/doc/pub/week37/html/._week37-bs038.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,64 +258,82 @@ MathJax.Hub.Config({

     

     

     

    -

    The bias-variance tradeoff

    +

    Same code but now with momentum gradient descent

    -

    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{D} \) consisting of the data -\( \mathbf{X}_\mathcal{D}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). -

    + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
     
    -

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

    +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x#+np.random.randn(n,1) -

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

    +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") -

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

    +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 30 -

    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]. -$$ +# define the gradient +training_gradient = grad(CostOLS) -

    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. -$$ +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients + print(iter,gradients[0],gradients[1]) +print("theta from own gd") +print(theta) -

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

    +# Now improve with momentum gradient descent +change = 0.0 +delta_momentum = 0.3 +for iter in range(Niterations): + # calculate gradient + gradients = training_gradient(theta) + # calculate update + new_change = eta*gradients+delta_momentum*change + # take a step + theta -= new_change + # save the change + change = new_change + print(iter,gradients[0],gradients[1]) +print("theta from own gd wth momentum") +print(theta) +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    @@ -372,10 +357,6 @@ $$

  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs039.html b/doc/pub/week37/html/._week37-bs039.html index e9ebac869..7aadc4545 100644 --- a/doc/pub/week37/html/._week37-bs039.html +++ b/doc/pub/week37/html/._week37-bs039.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,13 +258,68 @@ MathJax.Hub.Config({

     

     

     

    -

    A way to Read the Bias-Variance Tradeoff

    +

    But none of these can compete with Newton's method

    + + + +
    +
    +
    +
    +
    +
    # Using Newton's method
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(beta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +# Note that here the Hessian does not depend on the parameters beta
    +invH = np.linalg.pinv(H)
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +beta = np.random.randn(2,1)
    +Niterations = 5
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(beta)
    +    beta -= invH @ gradients
    +    print(iter,gradients[0],gradients[1])
    +print("beta from own Newton code")
    +print(beta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -
    -

    -
    -

    @@ -320,11 +342,6 @@ MathJax.Hub.Config({

  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs040.html b/doc/pub/week37/html/._week37-bs040.html index 4cb52fe6e..e6c23f356 100644 --- a/doc/pub/week37/html/._week37-bs040.html +++ b/doc/pub/week37/html/._week37-bs040.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,7 +258,9 @@ MathJax.Hub.Config({

     

     

     

    -

    Example code for Bias-Variance tradeoff

    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    +
    @@ -299,60 +268,79 @@ MathJax.Hub.Config({
    -
    import matplotlib.pyplot as plt
    +  
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
     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
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
     
    -np.random.seed(2018)
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
     
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,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)
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
     
    -# 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)
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
     
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
     
    -# 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)
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
     
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
     
    -# 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.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
     plt.show()
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
     
    @@ -389,12 +377,6 @@ plt.show()
  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • 50
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs041.html b/doc/pub/week37/html/._week37-bs041.html index 7112b2e60..ee18c3199 100644 --- a/doc/pub/week37/html/._week37-bs041.html +++ b/doc/pub/week37/html/._week37-bs041.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,7 +258,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Understanding what happens

    +

    Same code but now with momentum gradient descent

    @@ -299,52 +266,73 @@ MathJax.Hub.Config({
    -
    import matplotlib.pyplot as plt
    +  
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
     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
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
     
    -np.random.seed(2018)
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
     
    -n = 40
    -n_boostraps = 100
    -maxdegree = 14
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
     
     
    -# 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)
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
     
    -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()
    +theta = np.random.randn(2,1)
     
    -    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]))
    +change = 0.0
    +delta_momentum = 0.3
     
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    +for epoch in range(n_epochs):
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        # calculate update
    +        new_change = eta*gradients+delta_momentum*change
    +        # take a step
    +        theta -= new_change
    +        # save the change
    +        change = new_change
    +print("theta from own sdg with momentum")
    +print(theta)
     
    @@ -380,13 +368,6 @@ plt.show()
  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • 50
  • -
  • 51
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs042.html b/doc/pub/week37/html/._week37-bs042.html index fb72e3cd7..ee24d5f87 100644 --- a/doc/pub/week37/html/._week37-bs042.html +++ b/doc/pub/week37/html/._week37-bs042.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -290,39 +257,79 @@ MathJax.Hub.Config({

     

     

     

    - -

    Summing up

    + +

    Similar (second order function now) problem but now with AdaGrad

    -

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

    + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
     
    -

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

    +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) -

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

    +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x -

    You may also find this recent article of interest.

    +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-8 +for epoch in range(n_epochs): + Giter = 0.0 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + Giter += gradients*gradients + update = gradients*eta/(delta+np.sqrt(Giter)) + theta -= update +print("theta from own AdaGrad") +print(theta) +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Running this code we note an almost perfect agreement with the results from matrix inversion.

    @@ -342,14 +349,6 @@ flexible statistical methods have higher variance.

  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • 50
  • -
  • 51
  • -
  • 52
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs043.html b/doc/pub/week37/html/._week37-bs043.html index ee91c67f7..95d62990c 100644 --- a/doc/pub/week37/html/._week37-bs043.html +++ b/doc/pub/week37/html/._week37-bs043.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,25 +258,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Another Example from Scikit-Learn's Repository

    - -

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

    - +

    RMSprop for adaptive learning rate with Stochastic Gradient Descent

    @@ -317,55 +266,60 @@ training data.
    -
    #print(__doc__)
    -
    +  
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
     import numpy as np
    +import autograd.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
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
     
     
    -def true_fun(X):
    -    return np.cos(1.5 * np.pi * X)
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
     
    -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()
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameter rho
    +rho = 0.99
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +	# Accumulated gradient
    +	# Scaling with rho the new and the previous results
    +        Giter = (rho*Giter+(1-rho)*gradients*gradients)
    +	# Taking the diagonal only and inverting
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +	# Hadamard product
    +        theta -= update
    +print("theta from own RMSprop")
    +print(theta)
     
    @@ -399,15 +353,6 @@ plt.show()
  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • 50
  • -
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • ...
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs044.html b/doc/pub/week37/html/._week37-bs044.html index d0e16853e..8bebe3729 100644 --- a/doc/pub/week37/html/._week37-bs044.html +++ b/doc/pub/week37/html/._week37-bs044.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -290,24 +257,90 @@ MathJax.Hub.Config({

     

     

     

    - -

    Various steps in cross-validation

    + +

    And finally ADAM

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980
    +beta1 = 0.9
    +beta2 = 0.999
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-7
    +iter = 0
    +for epoch in range(n_epochs):
    +    first_moment = 0.0
    +    second_moment = 0.0
    +    iter += 1
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        # Computing moments first
    +        first_moment = beta1*first_moment + (1-beta1)*gradients
    +        second_moment = beta2*second_moment+(1-beta2)*gradients*gradients
    +        first_term = first_moment/(1.0-beta1**iter)
    +        second_term = second_moment/(1.0-beta2**iter)
    +	# Scaling with rho the new and the previous results
    +        update = eta*first_term/(np.sqrt(second_term)+delta)
    +        theta -= update
    +print("theta from own ADAM")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    @@ -325,14 +358,6 @@ cross-validation (LOOCV).

  • 44
  • 45
  • 46
  • -
  • 47
  • -
  • 48
  • -
  • 49
  • -
  • 50
  • -
  • 51
  • -
  • 52
  • -
  • 53
  • -
  • 54
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs045.html b/doc/pub/week37/html/._week37-bs045.html index de3fd74f6..74fba6165 100644 --- a/doc/pub/week37/html/._week37-bs045.html +++ b/doc/pub/week37/html/._week37-bs045.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -291,22 +258,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Cross-validation in brief

    - -

    For the various values of \( k \)

    +

    Material for the lab sessions

    +
    +
    +
      -
    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. +
    8. Exercise set for week 37
    9. +
    10. Work on project 1 +
    11. +
        +
      • For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.
      • +
    +
    +
    +

    diff --git a/doc/pub/week37/html/week37-bs.html b/doc/pub/week37/html/week37-bs.html index 39cfcfc18..541ecc814 100644 --- a/doc/pub/week37/html/week37-bs.html +++ b/doc/pub/week37/html/week37-bs.html @@ -40,159 +40,134 @@ doconce format html week37.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -228,58 +203,50 @@ MathJax.Hub.Config({ Contents @@ -306,7 +273,7 @@ MathJax.Hub.Config({
    -

    September 9, 2024

    +

    September 8-12, 2025


    @@ -333,7 +300,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 54
  • +
  • 46
  • »
  • @@ -347,7 +314,7 @@ MathJax.Hub.Config({ -->
    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week37/html/week37-reveal.html b/doc/pub/week37/html/week37-reveal.html index 7286e2f3f..c8984a7e6 100644 --- a/doc/pub/week37/html/week37-reveal.html +++ b/doc/pub/week37/html/week37-reveal.html @@ -181,7 +181,7 @@ MathJax.Hub.Config({
    -

    September 9, 2024

    +

    September 8-12, 2025


    @@ -189,7 +189,7 @@ MathJax.Hub.Config({
    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    @@ -197,1948 +197,1867 @@ MathJax.Hub.Config({

    Plans for week 37, lecture Monday

    -Material for the lecture on Monday September 9 +Plans and material for the lecture on Monday September 8

    -

    -

    - -

  • Statistical interpretation of Ridge and Lasso regression, see also slides from last week
  • - -

  • Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.
  • - -

  • Readings and Videos:
  • - +

    The family of gradient descent methods

    +
      +

    1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge
    2. +

    3. Improving gradient descent with momentum
    4. +

    5. Introducing stochastic gradient descent
    6. +

    7. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM + +
    8. +
    -

    Plans for week 37, lab sessions

    +

    Readings and Videos:

    +
    + +

    +

      +

    1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at https://www.deeplearningbook.org/contents/numerical.html and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html"
    2. +

    3. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
    4. +

    5. Video on gradient descent at https://www.youtube.com/watch?v=sDv4f4s2SB8
    6. +

    7. Video on Stochastic gradient descent at https://www.youtube.com/watch?v=vMh0zPT0tLI
    8. +
    +
    +
    + +
    +

    Material for lecture Monday September 8

    +
    + +
    +

    Gradient descent and revisiting Ordinary Least Squares from last week

    + +

    Last week we started with linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: +

    + +
      +

    1. An analytical solution (recall homework sets for week 35).
    2. +

    3. The gradient can be computed analytically.
    4. +

    5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
    6. +
    +

    +

    We revisit an example similar to what we had in the first homework set. We have a function of the type

    + + + +
    +
    +
    +
    +
    +
    x = 2*np.random.rand(m,1)
    +y = 4+3*x+np.random.randn(m,1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    with \( x_i \in [0,1] \) is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +

    +

     
    +$$ +h_\theta(x) = \boldsymbol{y} = \theta_0 + \theta_1 x, +$$ +

     
    + +

    such that

    +

     
    +$$ +\boldsymbol{y}_i = \theta_0 + \theta_1 x_i. +$$ +

     
    +

    + +
    +

    Gradient descent example

    + +

    Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\boldsymbol{y}} = (\boldsymbol{y}_1,\cdots,\boldsymbol{y}_n)^T \) and \( \theta = (\theta_0, \theta_1)^T \)

    + +

    It is convenient to write \( \mathbf{\boldsymbol{y}} = X\theta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by (we keep the intercept here)

    +

     
    +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ +

     
    + +

    The cost/loss/risk function is given by (

    +

     
    +$$ +C(\theta) = \frac{1}{n}||X\theta-\mathbf{y}||_{2}^{2} = \frac{1}{n}\sum_{i=1}^{100}\left[ (\theta_0 + \theta_1 x_i)^2 - 2 y_i (\theta_0 + \theta_1 x_i) + y_i^2\right] +$$ +

     
    + +

    and we want to find \( \theta \) such that \( C(\theta) \) is minimized.

    +
    + +
    +

    The derivative of the cost/loss function

    + +

    Computing \( \partial C(\theta) / \partial \theta_0 \) and \( \partial C(\theta) / \partial \theta_1 \) we can show that the gradient can be written as

    +

     
    +$$ +\nabla_{\theta} C(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = \frac{2}{n}X^T(X\theta - \mathbf{y}), +$$ +

     
    + +

    where \( X \) is the design matrix defined above.

    +
    + +
    +

    The Hessian matrix

    +

    The Hessian matrix of \( C(\theta) \) is given by

    +

     
    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X. +$$ +

     
    + +

    This result implies that \( C(\theta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite.

    +
    + +
    +

    Simple program

    + +

    We can now write a program that minimizes \( C(\theta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to

    +

     
    +$$ +\theta_{k+1} = \theta_k - \gamma \nabla_\theta C(\theta_k), \ k=0,1,\cdots +$$ +

     
    + +

    We can use the expression we computed for the gradient and let use a +\( \theta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\theta C(\theta_k) || \leq \epsilon = 10^{-8} \). Note that the code below does not include the latter stop criterion. +

    + +

    And finally we can compare our solution for \( \theta \) with the analytic result given by +\( \theta= (X^TX)^{-1} X^T \mathbf{y} \). +

    +
    + +
    +

    Gradient Descent Example

    + +

    Here our simple example

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +# Hessian matrix
    +H = (2.0/n)* X.T @ X
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y
    +print(theta_linreg)
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +for iter in range(Niterations):
    +    gradient = (2.0/n)*X.T @ (X @ theta-y)
    +    theta -= eta*gradient
    +
    +print(theta)
    +xnew = np.array([[0],[2]])
    +xbnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = xbnew.dot(theta)
    +ypredict2 = xbnew.dot(theta_linreg)
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Gradient descent and Ridge

    + +

    We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \theta \),

    +

     
    +$$ +C_{\text{ridge}}(\theta) = \frac{1}{n}||X\theta -\mathbf{y}||^2 + \lambda ||\theta||^2, \ \lambda \geq 0. +$$ +

     
    + +

    In order to minimize \( C_{\text{ridge}}(\theta) \) using GD we adjust the gradient as follows

    +

     
    +$$ +\nabla_\theta C_{\text{ridge}}(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \theta_0 \\ \theta_1\end{bmatrix} = 2 (\frac{1}{n}X^T(X\theta - \mathbf{y})+\lambda \theta). +$$ +

     
    + +

    We can easily extend our program to minimize \( C_{\text{ridge}}(\theta) \) using gradient descent and compare with the analytical solution given by

    +

     
    +$$ +\theta_{\text{ridge}} = \left(X^T X + n\lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ +

     
    +

    + +
    +

    The Hessian matrix for Ridge Regression

    +

    The Hessian matrix of Ridge Regression for our simple example is given by

    +

     
    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X+2\lambda\boldsymbol{I}. +$$ +

     
    + +

    This implies that the Hessian matrix is positive definite, hence the stationary point is a +minimum. +Note that the Ridge cost function is convex being a sum of two convex +functions. Therefore, the stationary point is a global +minimum of this function. +

    +
    + +
    +

    Program example for gradient descent with Ridge Regression

    + + +
    +
    +
    +
    +
    +
    from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +
    +#Ridge parameter lambda
    +lmbda  = 0.001
    +Id = n*lmbda* np.eye(XT_X.shape[0])
    +
    +# Hessian matrix
    +H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +
    +theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y
    +print(theta_linreg)
    +# Start plain gradient descent
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta
    +    theta -= eta*gradients
    +
    +print(theta)
    +ypredict = X @ theta
    +ypredict2 = X @ theta_linreg
    +plt.plot(x, ypredict, "r-")
    +plt.plot(x, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example for Ridge')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Using gradient descent methods, limitations

    + +
      +

    • Gradient descent (GD) finds local minima of our function. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
    • +

    • GD is sensitive to initial conditions. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
    • +

    • Gradients are computationally expensive to calculate for large datasets. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, \( E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2 \); for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over all \( n \) data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called "mini batches". This has the added benefit of introducing stochasticity into our algorithm.
    • +

    • GD is very sensitive to choices of learning rates. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would adaptively choose the learning rates to match the landscape.
    • +

    • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
    • +

    • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
    • +
    +
    + +
    +

    Improving gradient descent with momentum

    + +

    We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent.

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# take a step
    +		solution = solution - step_size * gradient
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# perform the gradient descent search
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Same code but now with momentum gradient descent

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# keep track of the change
    +	change = 0.0
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# calculate update
    +		new_change = step_size * gradient + momentum * change
    +		# take a step
    +		solution = solution - new_change
    +		# save the change
    +		change = new_change
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# define momentum
    +momentum = 0.3
    +# perform the gradient descent search with momentum
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent +
    + +
    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    +
    + +
    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    +
    + +
    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +

     
    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

     
    +

    + +
    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +

     
    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

     
    + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    +
    + +
    +

    SGD example

    +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +

     
    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ +

     
    +

    + +
    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +

     
    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ +

     
    + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    +
    + +
    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    +
    + +
    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    +
    + +
    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. Such approaches are +also called scaling. There are many such ways to scale the learning +rate +and discussions here. See +also +https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1 +for a discussion of different scaling functions for the learning rate. +

    +
    + +
    +

    Time decay rate

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function

     
    +$$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ +

     
    goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Code with a Number of Minibatches which varies

    + +

    In the code here we vary the number of mini-batches.

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. +

    +
    + +
    +

    Momentum based GD

    + +

    The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows +

    + +

     
    +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\tag{1} +\end{align} +$$ +

     
    + +

    where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is +

    + +

     
    +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ +

     
    + +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    +
    + +
    +

    More on momentum based approaches

    + +

    Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by +

    + +

     
    +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ +

     
    + +

    We can discretize this equation in the usual way to get

    + +

     
    +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ +

     
    + +

    Rearranging this equation, we can rewrite this as

    + +

     
    +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ +

     
    +

    + +
    +

    Momentum parameter

    + +

    Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: +

    + +

     
    +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ +

     
    + +

    Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    + +

    Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. +

    + +

    These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). +

    + +

    In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule +

    + +

     
    +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\tag{2} +\end{align} +$$ +

     
    + +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    +
    + +
    +

    Second moment of the gradient

    + +

    In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. +

    + +

    Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and +ADAM. +

    +
    + +
    +

    RMS prop

    + +

    In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by +

    + +

     
    +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ +

     
    + +

    where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. +

    +
    + +
    +

    ADAM optimizer

    + +

    A related algorithm is the ADAM optimizer. In +ADAM, we keep a running average of +both the first and second moment of the gradient and use this +information to adaptively change the learning rate for different +parameters. The method isefficient when working with large +problems involving lots data and/or parameters. It is a combination of the +gradient descent with momentum algorithm and the RMSprop algorithm +discussed above. +

    + +

    In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) +

    + +

     
    +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\tag{5} +\end{align} +$$ +

     
    + +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    + +

    Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - +(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by +

    + +

     
    +$$ +\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ +

     
    +

    + +
    +

    Algorithms and codes for Adagrad, RMSprop and Adam

    + +

    The algorithms we have implemented are well described in the text by Goodfellow, Bengio and Courville, chapter 8.

    + +

    The codes which implement these algorithms are discussed below here.

    +
    + +
    +

    Practical tips

    + +
      +

    • Randomize the data when making mini-batches. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
    • +

    • Transform your inputs. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
    • +

    • Monitor the out-of-sample performance. Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This early stopping significantly improves performance in many settings.
    • +

    • Adaptive optimization methods don't always have good generalization. Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
    • +
    +
    + +
    +

    Sneaking in automatic differentiation using Autograd

    + +

    We anticipate our discussions to come in connection with neural networks and automatic differentiation +by showing how we can use autograd for the cases above. Later we will replace autograd with JAX. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x#+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 30
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd")
    +print(theta)
    +
    +# Now improve with momentum gradient descent
    +change = 0.0
    +delta_momentum = 0.3
    +for iter in range(Niterations):
    +    # calculate gradient
    +    gradients = training_gradient(theta)
    +    # calculate update
    +    new_change = eta*gradients+delta_momentum*change
    +    # take a step
    +    theta -= new_change
    +    # save the change
    +    change = new_change
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd wth momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    But none of these can compete with Newton's method

    + + + +
    +
    +
    +
    +
    +
    # Using Newton's method
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(beta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +# Note that here the Hessian does not depend on the parameters beta
    +invH = np.linalg.pinv(H)
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +beta = np.random.randn(2,1)
    +Niterations = 5
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(beta)
    +    beta -= invH @ gradients
    +    print(iter,gradients[0],gradients[1])
    +print("beta from own Newton code")
    +print(beta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +change = 0.0
    +delta_momentum = 0.3
    +
    +for epoch in range(n_epochs):
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        # calculate update
    +        new_change = eta*gradients+delta_momentum*change
    +        # take a step
    +        theta -= new_change
    +        # save the change
    +        change = new_change
    +print("theta from own sdg with momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Similar (second order function now) problem but now with AdaGrad

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        Giter += gradients*gradients
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +        theta -= update
    +print("theta from own AdaGrad")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Running this code we note an almost perfect agreement with the results from matrix inversion.

    +
    + +
    +

    RMSprop for adaptive learning rate with Stochastic Gradient Descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameter rho
    +rho = 0.99
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +	# Accumulated gradient
    +	# Scaling with rho the new and the previous results
    +        Giter = (rho*Giter+(1-rho)*gradients*gradients)
    +	# Taking the diagonal only and inverting
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +	# Hadamard product
    +        theta -= update
    +print("theta from own RMSprop")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    And finally ADAM

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980
    +beta1 = 0.9
    +beta2 = 0.999
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-7
    +iter = 0
    +for epoch in range(n_epochs):
    +    first_moment = 0.0
    +    second_moment = 0.0
    +    iter += 1
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        # Computing moments first
    +        first_moment = beta1*first_moment + (1-beta1)*gradients
    +        second_moment = beta2*second_moment+(1-beta2)*gradients*gradients
    +        first_term = first_moment/(1.0-beta1**iter)
    +        second_term = second_moment/(1.0-beta2**iter)
    +	# Scaling with rho the new and the previous results
    +        update = eta*first_term/(np.sqrt(second_term)+delta)
    +        theta -= update
    +print("theta from own ADAM")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Material for the lab sessions

    Material for the lab sessions on Tuesday and Wednesday

    -

      - -

    • Calculations of expectation values
    • - -

    • Discussion of resampling techniques
    • - +

      1. Exercise set for week 37
      2. - -

      3. Work on project 1
      4. - -

      5. Video of exercise sessions week 37
      6. +

      7. Work on project 1 +
      8. +

        • For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.
        -
    -
    - -
    -

    Material for lecture Monday September 9

    -
    - -
    -

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

     
    - -

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    -
    - -
    -

    More basic Statistics and Bayes' theorem

    - -

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. -

    - -

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    - -

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. -The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \). -

    - -
    -Union of events is given by

    -

     
    -$$ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -$$ -

     
    -

    - - -
    -The product rule (aka joint probability) is given by -

    -

     
    -$$ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -$$ -

     
    - -

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    -
    - -

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    -
    - -
    -

    Marginal Probability

    - -

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    -
    - -

    -

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

     
    -

    -
    - -
    -

    Conditional Probability

    - -

    The conditional probability, if \( p(Y) > 0 \), is

    -
    - -

    -

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

     
    -

    -
    - -
    -

    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.

    - -

    Let us try to illustrate Bayes' theorem through an example.

    -
    - -
    -

    Example of Usage of Bayes' theorem

    - -

    Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable \( X \). It takes binary -values with \( X=1 \) representing a positive event and \( X=0 \) being a -negative event. We reserve \( Y \) as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). -

    - -

    We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.

    - -

    Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have

    - -

     
    -$$ -p(X=1\vert Y=1) =0.8. -$$ -

     
    - -

    This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer. -It is however not correct, as the following Bayesian analysis shows. -

    -
    - -
    -

    Doing it correctly

    - -

    If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is -

    - -

     
    -$$ -p(Y=1) =0.004. -$$ -

     
    - -

    We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have

    -

     
    -$$ -p(X=1\vert Y=0) =0.1. -$$ -

     
    - -

    Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute

    - -

     
    -$$ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -$$ -

     
    - -

    That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!

    -
    - -
    -

    Bayes' Theorem and Ridge and Lasso Regression

    - -

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

    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 \( \mathbb{E}[x_i] \). Each mean value \( \mathbb{E}[x_i] \) -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 \( \mathbb{E}[x_i]=x_i \) in the discussion -which follows. We do the same for \( \mathbb{E}[z]=z \). -

    - -

    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 central limit theorem leads 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 (the so-called Bessel correction) -

    -

     
    -$$ - \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. Keep -in mind that we have assumed that the variables \( x \) are independent -and identically distributed. This is obviously not always the -case. For example, the random numbers (or better pseudorandom numbers) -we generate in various calculations do always exhibit some -correlations. -

    - -

    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 form /analytic expression for -\( \tilde{p}(x) \). -

    -
    - -
    -

    Confidence Intervals

    - -

    Confidence intervals are used in statistics and represent 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. -

    - -

    In the exercises this week we show 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 can 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. -

    -
    - -
    -

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

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from time import time
    -from scipy.stats import norm
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples 
    -# Bootstrap algorithm
    -def bootstrap(data, datapoints):
    -    t = np.zeros(datapoints)
    -    n = len(data)
    -    # non-parametric bootstrap         
    -    for i in range(datapoints):
    -        t[i] = np.mean(data[np.random.randint(0,n,n)])
    -    # analysis    
    -    print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))
    -    return t
    -
    -# We set the mean value to 100 and the standard deviation to 15
    -mu, sigma = 100, 15
    -datapoints = 10000
    -# We generate random numbers according to the normal distribution
    -x = mu + sigma*np.random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, 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 (normalized data if density = True)
    -n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)
    -# add a 'best fit' line  
    -y = norm.pdf(binsboot, np.mean(t), np.std(t))
    -lt = plt.plot(binsboot, y, 'b', linewidth=1)
    -plt.xlabel('x')
    -plt.ylabel('Probability')
    -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{D} \) consisting of the data -\( \mathbf{X}_\mathcal{D}=\{(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

    - -

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

    -
    - -
    -

    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=False).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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Note that we kept the intercept column in the fitting here. This means that we need to set the intercept in the call to the Scikit-Learn function as False. Alternatively, we could have set up the design matrix \( X \) without the first column of ones.

    -
    - -
    -

    The same example but now with cross-validation

    - -

    In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error.

    - - -
    -
    -
    -
    -
    -
    # 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(fit_intercept=False)
    -# 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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Material for the lab sessions

    -
    - -
    -

    Linking the regression analysis with a statistical interpretation

    - -

    We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -\( \beta \). -

    - -

    The -advantage of doing linear regression is that we actually end up with -analytical expressions for several statistical quantities. -Standard least squares and Ridge regression allow us to -derive quantities like the variance and other expectation values in a -rather straightforward way. -

    - -

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

    -

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

     
    - -

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

    - -

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

    -
    - -
    -

    Assumptions made

    - -

    The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describe our data -

    -

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

     
    - -

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

    -

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

     
    -

    - -
    -

    Expectation value and variance

    - -

    We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)

    -

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

     
    - -

    while -its variance is -

    -

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

     
    - -

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). -

    -
    - -
    -

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

    - -

    With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value

    -

     
    -$$ -\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. -$$ -

     
    - -

    This means that the estimator of the regression parameters is unbiased.

    - -

    We can also calculate the variance

    - -

    The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is

    -

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

     
    - -

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

    - -

    In a similar way, we can obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, allowing us again to define a confidence interval. -

    - -

    It is rather straightforward to show that

    -

     
    -$$ -\mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}. -$$ -

     
    - -

    We see clearly that -\( \mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big] \not= \hat{\boldsymbol{\beta}}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). -

    - -

    We can also compute the variance as

    - -

     
    -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, -$$ -

     
    - -

    and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.

    - -

    With this, we can compute the difference

    - -

     
    -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}]-\mbox{Var}(\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. -$$ -

     
    - -

    The difference is non-negative definite since each component of the -matrix product is non-negative definite. -This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. -

    - -

    For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.

    diff --git a/doc/pub/week37/html/week37-solarized.html b/doc/pub/week37/html/week37-solarized.html index 9f9f47f47..f1b99880d 100644 --- a/doc/pub/week37/html/week37-solarized.html +++ b/doc/pub/week37/html/week37-solarized.html @@ -67,159 +67,134 @@ div.toc p,a { 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -254,7 +229,7 @@ MathJax.Hub.Config({
    -

    September 9, 2024

    +

    September 8-12, 2025


    @@ -264,1774 +239,1790 @@ MathJax.Hub.Config({

    Plans for week 37, lecture Monday

    -Material for the lecture on Monday September 9 +Plans and material for the lecture on Monday September 8

    -

    -
  • Statistical interpretation of Ridge and Lasso regression, see also slides from last week
  • -
  • Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.
  • -
  • Readings and Videos:
  • - +

    The family of gradient descent methods

    +
      +
    1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge
    2. +
    3. Improving gradient descent with momentum
    4. +
    5. Introducing stochastic gradient descent
    6. +
    7. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM + +
    8. +
    +
    + +









    +

    Readings and Videos:

    +
    + +

    +

      +
    1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at https://www.deeplearningbook.org/contents/numerical.html and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html"
    2. +
    3. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
    4. +
    5. Video on gradient descent at https://www.youtube.com/watch?v=sDv4f4s2SB8
    6. +
    7. Video on Stochastic gradient descent at https://www.youtube.com/watch?v=vMh0zPT0tLI
    8. +










    -

    Plans for week 37, lab sessions

    +

    Material for lecture Monday September 8

    + + +

    Gradient descent and revisiting Ordinary Least Squares from last week

    + +

    Last week we started with linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: +

    + +
      +
    1. An analytical solution (recall homework sets for week 35).
    2. +
    3. The gradient can be computed analytically.
    4. +
    5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
    6. +
    +

    We revisit an example similar to what we had in the first homework set. We have a function of the type

    + + + +
    +
    +
    +
    +
    +
    x = 2*np.random.rand(m,1)
    +y = 4+3*x+np.random.randn(m,1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    with \( x_i \in [0,1] \) is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +

    +$$ +h_\theta(x) = \boldsymbol{y} = \theta_0 + \theta_1 x, +$$ + +

    such that

    +$$ +\boldsymbol{y}_i = \theta_0 + \theta_1 x_i. +$$ + + + +

    Gradient descent example

    + +

    Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\boldsymbol{y}} = (\boldsymbol{y}_1,\cdots,\boldsymbol{y}_n)^T \) and \( \theta = (\theta_0, \theta_1)^T \)

    + +

    It is convenient to write \( \mathbf{\boldsymbol{y}} = X\theta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by (we keep the intercept here)

    +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ + +

    The cost/loss/risk function is given by (

    +$$ +C(\theta) = \frac{1}{n}||X\theta-\mathbf{y}||_{2}^{2} = \frac{1}{n}\sum_{i=1}^{100}\left[ (\theta_0 + \theta_1 x_i)^2 - 2 y_i (\theta_0 + \theta_1 x_i) + y_i^2\right] +$$ + +

    and we want to find \( \theta \) such that \( C(\theta) \) is minimized.

    + +









    +

    The derivative of the cost/loss function

    + +

    Computing \( \partial C(\theta) / \partial \theta_0 \) and \( \partial C(\theta) / \partial \theta_1 \) we can show that the gradient can be written as

    +$$ +\nabla_{\theta} C(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = \frac{2}{n}X^T(X\theta - \mathbf{y}), +$$ + +

    where \( X \) is the design matrix defined above.

    + +









    +

    The Hessian matrix

    +

    The Hessian matrix of \( C(\theta) \) is given by

    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X. +$$ + +

    This result implies that \( C(\theta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite.

    + +









    +

    Simple program

    + +

    We can now write a program that minimizes \( C(\theta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to

    +$$ +\theta_{k+1} = \theta_k - \gamma \nabla_\theta C(\theta_k), \ k=0,1,\cdots +$$ + +

    We can use the expression we computed for the gradient and let use a +\( \theta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\theta C(\theta_k) || \leq \epsilon = 10^{-8} \). Note that the code below does not include the latter stop criterion. +

    + +

    And finally we can compare our solution for \( \theta \) with the analytic result given by +\( \theta= (X^TX)^{-1} X^T \mathbf{y} \). +

    + +









    +

    Gradient Descent Example

    + +

    Here our simple example

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +# Hessian matrix
    +H = (2.0/n)* X.T @ X
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y
    +print(theta_linreg)
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +for iter in range(Niterations):
    +    gradient = (2.0/n)*X.T @ (X @ theta-y)
    +    theta -= eta*gradient
    +
    +print(theta)
    +xnew = np.array([[0],[2]])
    +xbnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = xbnew.dot(theta)
    +ypredict2 = xbnew.dot(theta_linreg)
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Gradient descent and Ridge

    + +

    We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \theta \),

    +$$ +C_{\text{ridge}}(\theta) = \frac{1}{n}||X\theta -\mathbf{y}||^2 + \lambda ||\theta||^2, \ \lambda \geq 0. +$$ + +

    In order to minimize \( C_{\text{ridge}}(\theta) \) using GD we adjust the gradient as follows

    +$$ +\nabla_\theta C_{\text{ridge}}(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \theta_0 \\ \theta_1\end{bmatrix} = 2 (\frac{1}{n}X^T(X\theta - \mathbf{y})+\lambda \theta). +$$ + +

    We can easily extend our program to minimize \( C_{\text{ridge}}(\theta) \) using gradient descent and compare with the analytical solution given by

    +$$ +\theta_{\text{ridge}} = \left(X^T X + n\lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ + + +









    +

    The Hessian matrix for Ridge Regression

    +

    The Hessian matrix of Ridge Regression for our simple example is given by

    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X+2\lambda\boldsymbol{I}. +$$ + +

    This implies that the Hessian matrix is positive definite, hence the stationary point is a +minimum. +Note that the Ridge cost function is convex being a sum of two convex +functions. Therefore, the stationary point is a global +minimum of this function. +

    + +









    +

    Program example for gradient descent with Ridge Regression

    + + +
    +
    +
    +
    +
    +
    from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +
    +#Ridge parameter lambda
    +lmbda  = 0.001
    +Id = n*lmbda* np.eye(XT_X.shape[0])
    +
    +# Hessian matrix
    +H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +
    +theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y
    +print(theta_linreg)
    +# Start plain gradient descent
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta
    +    theta -= eta*gradients
    +
    +print(theta)
    +ypredict = X @ theta
    +ypredict2 = X @ theta_linreg
    +plt.plot(x, ypredict, "r-")
    +plt.plot(x, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example for Ridge')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Using gradient descent methods, limitations

    + +
      +
    • Gradient descent (GD) finds local minima of our function. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
    • +
    • GD is sensitive to initial conditions. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
    • +
    • Gradients are computationally expensive to calculate for large datasets. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, \( E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2 \); for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over all \( n \) data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called "mini batches". This has the added benefit of introducing stochasticity into our algorithm.
    • +
    • GD is very sensitive to choices of learning rates. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would adaptively choose the learning rates to match the landscape.
    • +
    • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
    • +
    • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
    • +
    +









    +

    Improving gradient descent with momentum

    + +

    We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent.

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# take a step
    +		solution = solution - step_size * gradient
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# perform the gradient descent search
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# keep track of the change
    +	change = 0.0
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# calculate update
    +		new_change = step_size * gradient + momentum * change
    +		# take a step
    +		solution = solution - new_change
    +		# save the change
    +		change = new_change
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# define momentum
    +momentum = 0.3
    +# perform the gradient descent search with momentum
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent + +









    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    + +









    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    + +









    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + + +









    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    + +









    +

    SGD example

    +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + + +









    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    + +









    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    + +









    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    + +









    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. Such approaches are +also called scaling. There are many such ways to scale the learning +rate +and discussions here. See +also +https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1 +for a discussion of different scaling functions for the learning rate. +

    + +









    +

    Time decay rate

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Code with a Number of Minibatches which varies

    + +

    In the code here we vary the number of mini-batches.

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. +

    + +









    +

    Momentum based GD

    + +

    The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows +

    + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\label{_auto1} +\end{align} +$$ + +

    where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is +

    + +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    + +









    +

    More on momentum based approaches

    + +

    Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by +

    + +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ + +

    We can discretize this equation in the usual way to get

    + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

    Rearranging this equation, we can rewrite this as

    + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ + + +









    +

    Momentum parameter

    + +

    Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: +

    + +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ + +

    Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    + +

    Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. +

    + +

    These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). +

    + +

    In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule +

    + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\label{_auto2} +\end{align} +$$ + +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    + +









    +

    Second moment of the gradient

    + +

    In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. +

    + +

    Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and +ADAM. +

    + +









    +

    RMS prop

    + +

    In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by +

    + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

    where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. +

    + +









    +

    ADAM optimizer

    + +

    A related algorithm is the ADAM optimizer. In +ADAM, we keep a running average of +both the first and second moment of the gradient and use this +information to adaptively change the learning rate for different +parameters. The method isefficient when working with large +problems involving lots data and/or parameters. It is a combination of the +gradient descent with momentum algorithm and the RMSprop algorithm +discussed above. +

    + +

    In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) +

    + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\label{_auto5} +\end{align} +$$ + +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    + +

    Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - +(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by +

    + +$$ +\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + + +









    +

    Algorithms and codes for Adagrad, RMSprop and Adam

    + +

    The algorithms we have implemented are well described in the text by Goodfellow, Bengio and Courville, chapter 8.

    + +

    The codes which implement these algorithms are discussed below here.

    + +









    +

    Practical tips

    + +
      +
    • Randomize the data when making mini-batches. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
    • +
    • Transform your inputs. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
    • +
    • Monitor the out-of-sample performance. Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This early stopping significantly improves performance in many settings.
    • +
    • Adaptive optimization methods don't always have good generalization. Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
    • +
    +









    +

    Sneaking in automatic differentiation using Autograd

    + +

    We anticipate our discussions to come in connection with neural networks and automatic differentiation +by showing how we can use autograd for the cases above. Later we will replace autograd with JAX. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x#+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 30
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd")
    +print(theta)
    +
    +# Now improve with momentum gradient descent
    +change = 0.0
    +delta_momentum = 0.3
    +for iter in range(Niterations):
    +    # calculate gradient
    +    gradients = training_gradient(theta)
    +    # calculate update
    +    new_change = eta*gradients+delta_momentum*change
    +    # take a step
    +    theta -= new_change
    +    # save the change
    +    change = new_change
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd wth momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    But none of these can compete with Newton's method

    + + + +
    +
    +
    +
    +
    +
    # Using Newton's method
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(beta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +# Note that here the Hessian does not depend on the parameters beta
    +invH = np.linalg.pinv(H)
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +beta = np.random.randn(2,1)
    +Niterations = 5
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(beta)
    +    beta -= invH @ gradients
    +    print(iter,gradients[0],gradients[1])
    +print("beta from own Newton code")
    +print(beta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +change = 0.0
    +delta_momentum = 0.3
    +
    +for epoch in range(n_epochs):
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        # calculate update
    +        new_change = eta*gradients+delta_momentum*change
    +        # take a step
    +        theta -= new_change
    +        # save the change
    +        change = new_change
    +print("theta from own sdg with momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Similar (second order function now) problem but now with AdaGrad

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        Giter += gradients*gradients
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +        theta -= update
    +print("theta from own AdaGrad")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Running this code we note an almost perfect agreement with the results from matrix inversion.

    + +









    +

    RMSprop for adaptive learning rate with Stochastic Gradient Descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameter rho
    +rho = 0.99
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +	# Accumulated gradient
    +	# Scaling with rho the new and the previous results
    +        Giter = (rho*Giter+(1-rho)*gradients*gradients)
    +	# Taking the diagonal only and inverting
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +	# Hadamard product
    +        theta -= update
    +print("theta from own RMSprop")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    And finally ADAM

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980
    +beta1 = 0.9
    +beta2 = 0.999
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-7
    +iter = 0
    +for epoch in range(n_epochs):
    +    first_moment = 0.0
    +    second_moment = 0.0
    +    iter += 1
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        # Computing moments first
    +        first_moment = beta1*first_moment + (1-beta1)*gradients
    +        second_moment = beta2*second_moment+(1-beta2)*gradients*gradients
    +        first_term = first_moment/(1.0-beta1**iter)
    +        second_term = second_moment/(1.0-beta2**iter)
    +	# Scaling with rho the new and the previous results
    +        update = eta*first_term/(np.sqrt(second_term)+delta)
    +        theta -= update
    +print("theta from own ADAM")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Material for the lab sessions

    Material for the lab sessions on Tuesday and Wednesday

    +

      +
    1. Exercise set for week 37
    2. +
    3. Work on project 1 +
      • -
      • Calculations of expectation values
      • -
      • Discussion of resampling techniques
      • -
      • Exercise set for week 37
      • -
      • Work on project 1
      • -
      • Video of exercise sessions week 37
      • For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.
      +
    - -









    -

    Material for lecture Monday September 9

    - -









    -

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

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    - -









    -

    More basic Statistics and Bayes' theorem

    - -

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. -

    - -

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    - -

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. -The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \). -

    - -
    -Union of events is given by -

    -$$ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -$$ -

    - - -
    -The product rule (aka joint probability) is given by -

    -$$ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -$$ - -

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    -
    - - -

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    - -









    -

    Marginal Probability

    - -

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    -
    - -

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

    - - -









    -

    Conditional Probability

    - -

    The conditional probability, if \( p(Y) > 0 \), is

    -
    - -

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

    - - -









    -

    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.

    - -

    Let us try to illustrate Bayes' theorem through an example.

    - -









    -

    Example of Usage of Bayes' theorem

    - -

    Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable \( X \). It takes binary -values with \( X=1 \) representing a positive event and \( X=0 \) being a -negative event. We reserve \( Y \) as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). -

    - -

    We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.

    - -

    Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have

    - -$$ -p(X=1\vert Y=1) =0.8. -$$ - -

    This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer. -It is however not correct, as the following Bayesian analysis shows. -

    - -









    -

    Doing it correctly

    - -

    If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is -

    - -$$ -p(Y=1) =0.004. -$$ - -

    We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have

    -$$ -p(X=1\vert Y=0) =0.1. -$$ - -

    Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute

    - -$$ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -$$ - -

    That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!

    - -









    -

    Bayes' Theorem and Ridge and Lasso Regression

    - -

    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: 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 \( \mathbb{E}[x_i] \). Each mean value \( \mathbb{E}[x_i] \) -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 \( \mathbb{E}[x_i]=x_i \) in the discussion -which follows. We do the same for \( \mathbb{E}[z]=z \). -

    - -

    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 central limit theorem leads 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 (the so-called Bessel correction) -

    -$$ - \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. Keep -in mind that we have assumed that the variables \( x \) are independent -and identically distributed. This is obviously not always the -case. For example, the random numbers (or better pseudorandom numbers) -we generate in various calculations do always exhibit some -correlations. -

    - -

    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 form /analytic expression for -\( \tilde{p}(x) \). -

    - -









    -

    Confidence Intervals

    - -

    Confidence intervals are used in statistics and represent 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. -

    - -

    In the exercises this week we show 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 can 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. -

    - -









    -

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

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from time import time
    -from scipy.stats import norm
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples 
    -# Bootstrap algorithm
    -def bootstrap(data, datapoints):
    -    t = np.zeros(datapoints)
    -    n = len(data)
    -    # non-parametric bootstrap         
    -    for i in range(datapoints):
    -        t[i] = np.mean(data[np.random.randint(0,n,n)])
    -    # analysis    
    -    print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))
    -    return t
    -
    -# We set the mean value to 100 and the standard deviation to 15
    -mu, sigma = 100, 15
    -datapoints = 10000
    -# We generate random numbers according to the normal distribution
    -x = mu + sigma*np.random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, 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 (normalized data if density = True)
    -n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)
    -# add a 'best fit' line  
    -y = norm.pdf(binsboot, np.mean(t), np.std(t))
    -lt = plt.plot(binsboot, y, 'b', linewidth=1)
    -plt.xlabel('x')
    -plt.ylabel('Probability')
    -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{D} \) consisting of the data -\( \mathbf{X}_\mathcal{D}=\{(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

    - -

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

    - -









    -

    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=False).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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Note that we kept the intercept column in the fitting here. This means that we need to set the intercept in the call to the Scikit-Learn function as False. Alternatively, we could have set up the design matrix \( X \) without the first column of ones.

    - - -

    The same example but now with cross-validation

    - -

    In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error.

    - - -
    -
    -
    -
    -
    -
    # 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(fit_intercept=False)
    -# 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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Material for the lab sessions

    - - -

    Linking the regression analysis with a statistical interpretation

    - -

    We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -\( \beta \). -

    - -

    The -advantage of doing linear regression is that we actually end up with -analytical expressions for several statistical quantities. -Standard least squares and Ridge regression allow us to -derive quantities like the variance and other expectation values in a -rather straightforward way. -

    - -

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

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

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

    - -

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

    - -









    -

    Assumptions made

    - -

    The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describe our data -

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

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

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









    -

    Expectation value and variance

    - -

    We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)

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

    while -its variance is -

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

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). -

    - -









    -

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

    - -

    With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value

    -$$ -\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. -$$ - -

    This means that the estimator of the regression parameters is unbiased.

    - -

    We can also calculate the variance

    - -

    The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is

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

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

    - -

    In a similar way, we can obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, allowing us again to define a confidence interval. -

    - -

    It is rather straightforward to show that

    -$$ -\mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}. -$$ - -

    We see clearly that -\( \mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big] \not= \hat{\boldsymbol{\beta}}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). -

    - -

    We can also compute the variance as

    - -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, -$$ - -

    and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.

    - -

    With this, we can compute the difference

    - -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}]-\mbox{Var}(\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. -$$ - -

    The difference is non-negative definite since each component of the -matrix product is non-negative definite. -This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. -

    - -

    For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.

    -
    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week37/html/week37.html b/doc/pub/week37/html/week37.html index 433634e84..3187de778 100644 --- a/doc/pub/week37/html/week37.html +++ b/doc/pub/week37/html/week37.html @@ -144,159 +144,134 @@ div.toc p,a { 2, None, 'plans-for-week-37-lecture-monday'), - ('Plans for week 37, lab sessions', + ('Readings and Videos:', 2, None, 'readings-and-videos'), + ('Material for lecture Monday September 8', 2, None, - 'plans-for-week-37-lab-sessions'), - ('Material for lecture Monday September 9', + 'material-for-lecture-monday-september-8'), + ('Gradient descent and revisiting Ordinary Least Squares from ' + 'last week', 2, None, - 'material-for-lecture-monday-september-9'), - ('Deriving OLS from a probability distribution', + 'gradient-descent-and-revisiting-ordinary-least-squares-from-last-week'), + ('Gradient descent example', 2, None, 'gradient-descent-example'), + ('The derivative of the cost/loss function', 2, None, - 'deriving-ols-from-a-probability-distribution'), - ('Independent and Identically Distrubuted (iid)', + 'the-derivative-of-the-cost-loss-function'), + ('The Hessian matrix', 2, None, 'the-hessian-matrix'), + ('Simple program', 2, None, 'simple-program'), + ('Gradient Descent Example', 2, None, 'gradient-descent-example'), + ('Gradient descent and Ridge', 2, None, - 'independent-and-identically-distrubuted-iid'), - ('Maximum Likelihood Estimation (MLE)', + 'gradient-descent-and-ridge'), + ('The Hessian matrix for Ridge Regression', 2, None, - 'maximum-likelihood-estimation-mle'), - ('A new Cost Function', 2, None, 'a-new-cost-function'), - ("More basic Statistics and Bayes' theorem", + 'the-hessian-matrix-for-ridge-regression'), + ('Program example for gradient descent with Ridge Regression', 2, None, - 'more-basic-statistics-and-bayes-theorem'), - ('Marginal Probability', 2, None, 'marginal-probability'), - ('Conditional Probability', 2, None, 'conditional-probability'), - ("Bayes' Theorem", 2, None, 'bayes-theorem'), - ("Interpretations of Bayes' Theorem", + 'program-example-for-gradient-descent-with-ridge-regression'), + ('Using gradient descent methods, limitations', 2, None, - 'interpretations-of-bayes-theorem'), - ("Example of Usage of Bayes' theorem", + 'using-gradient-descent-methods-limitations'), + ('Improving gradient descent with momentum', 2, None, - 'example-of-usage-of-bayes-theorem'), - ('Doing it correctly', 2, None, 'doing-it-correctly'), - ("Bayes' Theorem and Ridge and Lasso Regression", + 'improving-gradient-descent-with-momentum'), + ('Same code but now with momentum gradient descent', 2, None, - 'bayes-theorem-and-ridge-and-lasso-regression'), - ('Ridge and Bayes', 2, None, 'ridge-and-bayes'), - ('Lasso and Bayes', 2, None, 'lasso-and-bayes'), - ('Why resampling methods', 2, None, 'why-resampling-methods'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling approaches can be computationally expensive', + 'same-code-but-now-with-momentum-gradient-descent'), + ('Overview video on Stochastic Gradient Descent', 2, None, - 'resampling-approaches-can-be-computationally-expensive'), - ('Why resampling methods ?', 2, None, 'why-resampling-methods'), - ('Statistical analysis', 2, None, 'statistical-analysis'), - ('Resampling methods', 2, None, 'resampling-methods'), - ('Resampling methods: Bootstrap', + 'overview-video-on-stochastic-gradient-descent'), + ('Batches and mini-batches', 2, None, 'batches-and-mini-batches'), + ('Stochastic Gradient Descent (SGD)', 2, None, - 'resampling-methods-bootstrap'), - ('The Central Limit Theorem', + 'stochastic-gradient-descent-sgd'), + ('Stochastic Gradient Descent', 2, None, - 'the-central-limit-theorem'), - ('Finding the Limit', 2, None, 'finding-the-limit'), - ('Rewriting the $\\delta$-function', + 'stochastic-gradient-descent'), + ('Computation of gradients', 2, None, 'computation-of-gradients'), + ('SGD example', 2, None, 'sgd-example'), + ('The gradient step', 2, None, 'the-gradient-step'), + ('Simple example code', 2, None, 'simple-example-code'), + ('When do we stop?', 2, None, 'when-do-we-stop'), + ('Slightly different approach', 2, None, - 'rewriting-the-delta-function'), - ('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', + 'slightly-different-approach'), + ('Time decay rate', 2, None, 'time-decay-rate'), + ('Code with a Number of Minibatches which varies', 2, None, - 'standard-approach-based-on-the-normal-distribution'), - ('Resampling methods: Bootstrap background', + 'code-with-a-number-of-minibatches-which-varies'), + ('Replace or not', 2, None, 'replace-or-not'), + ('Momentum based GD', 2, None, 'momentum-based-gd'), + ('More on momentum based approaches', 2, None, - 'resampling-methods-bootstrap-background'), - ('Resampling methods: More Bootstrap background', + 'more-on-momentum-based-approaches'), + ('Momentum parameter', 2, None, 'momentum-parameter'), + ('Second moment of the gradient', 2, None, - 'resampling-methods-more-bootstrap-background'), - ('Resampling methods: Bootstrap approach', + 'second-moment-of-the-gradient'), + ('RMS prop', 2, None, 'rms-prop'), + ('"ADAM optimizer":"https://arxiv.org/abs/1412.6980"', 2, None, - 'resampling-methods-bootstrap-approach'), - ('Resampling methods: Bootstrap steps', + 'adam-optimizer-https-arxiv-org-abs-1412-6980'), + ('Algorithms and codes for Adagrad, RMSprop and Adam', 2, None, - 'resampling-methods-bootstrap-steps'), - ('Code example for the Bootstrap method', + 'algorithms-and-codes-for-adagrad-rmsprop-and-adam'), + ('Practical tips', 2, None, 'practical-tips'), + ('Sneaking in automatic differentiation using Autograd', 2, None, - 'code-example-for-the-bootstrap-method'), - ('Plotting the Histogram', 2, None, 'plotting-the-histogram'), - ('The bias-variance tradeoff', + 'sneaking-in-automatic-differentiation-using-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'the-bias-variance-tradeoff'), - ('A way to Read the Bias-Variance Tradeoff', + 'same-code-but-now-with-momentum-gradient-descent'), + ("But none of these can compete with Newton's method", 2, None, - 'a-way-to-read-the-bias-variance-tradeoff'), - ('Example code for Bias-Variance tradeoff', + 'but-none-of-these-can-compete-with-newton-s-method'), + ('Including Stochastic Gradient Descent with Autograd', 2, None, - 'example-code-for-bias-variance-tradeoff'), - ('Understanding what happens', + 'including-stochastic-gradient-descent-with-autograd'), + ('Same code but now with momentum gradient descent', 2, None, - 'understanding-what-happens'), - ('Summing up', 2, None, 'summing-up'), - ("Another Example from Scikit-Learn's Repository", + 'same-code-but-now-with-momentum-gradient-descent'), + ('Similar (second order function now) problem but now with ' + 'AdaGrad', 2, None, - 'another-example-from-scikit-learn-s-repository'), - ('Various steps in cross-validation', + 'similar-second-order-function-now-problem-but-now-with-adagrad'), + ('RMSprop for adaptive learning rate with Stochastic Gradient ' + 'Descent', 2, None, - 'various-steps-in-cross-validation'), - ('Cross-validation in brief', + 'rmsprop-for-adaptive-learning-rate-with-stochastic-gradient-descent'), + ('And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf"', 2, None, - 'cross-validation-in-brief'), - ('Code Example for Cross-validation and $k$-fold ' - 'Cross-validation', - 2, - None, - 'code-example-for-cross-validation-and-k-fold-cross-validation'), - ('More examples on bootstrap and cross-validation and errors', - 2, - None, - 'more-examples-on-bootstrap-and-cross-validation-and-errors'), - ('The same example but now with cross-validation', - 2, - None, - 'the-same-example-but-now-with-cross-validation'), + 'and-finally-adam-https-arxiv-org-pdf-1412-6980-pdf'), ('Material for the lab sessions', 2, None, - 'material-for-the-lab-sessions'), - ('Linking the regression analysis with a statistical ' - 'interpretation', - 2, - None, - 'linking-the-regression-analysis-with-a-statistical-interpretation'), - ('Assumptions made', 2, None, 'assumptions-made'), - ('Expectation value and variance', - 2, - None, - 'expectation-value-and-variance'), - ('Expectation value and variance for $\\boldsymbol{\\beta}$', - 2, - None, - 'expectation-value-and-variance-for-boldsymbol-beta')]} + 'material-for-the-lab-sessions')]} end of tocinfo --> @@ -331,7 +306,7 @@ MathJax.Hub.Config({
    -

    September 9, 2024

    +

    September 8-12, 2025


    @@ -341,1774 +316,1790 @@ MathJax.Hub.Config({

    Plans for week 37, lecture Monday

    -Material for the lecture on Monday September 9 +Plans and material for the lecture on Monday September 8

    -

    -
  • Statistical interpretation of Ridge and Lasso regression, see also slides from last week
  • -
  • Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.
  • -
  • Readings and Videos:
  • - +

    The family of gradient descent methods

    +
      +
    1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge
    2. +
    3. Improving gradient descent with momentum
    4. +
    5. Introducing stochastic gradient descent
    6. +
    7. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM + +
    8. +
    +
    + +









    +

    Readings and Videos:

    +
    + +

    +

      +
    1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at https://www.deeplearningbook.org/contents/numerical.html and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html"
    2. +
    3. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
    4. +
    5. Video on gradient descent at https://www.youtube.com/watch?v=sDv4f4s2SB8
    6. +
    7. Video on Stochastic gradient descent at https://www.youtube.com/watch?v=vMh0zPT0tLI
    8. +










    -

    Plans for week 37, lab sessions

    +

    Material for lecture Monday September 8

    + + +

    Gradient descent and revisiting Ordinary Least Squares from last week

    + +

    Last week we started with linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: +

    + +
      +
    1. An analytical solution (recall homework sets for week 35).
    2. +
    3. The gradient can be computed analytically.
    4. +
    5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
    6. +
    +

    We revisit an example similar to what we had in the first homework set. We have a function of the type

    + + + +
    +
    +
    +
    +
    +
    x = 2*np.random.rand(m,1)
    +y = 4+3*x+np.random.randn(m,1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    with \( x_i \in [0,1] \) is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +

    +$$ +h_\theta(x) = \boldsymbol{y} = \theta_0 + \theta_1 x, +$$ + +

    such that

    +$$ +\boldsymbol{y}_i = \theta_0 + \theta_1 x_i. +$$ + + + +

    Gradient descent example

    + +

    Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\boldsymbol{y}} = (\boldsymbol{y}_1,\cdots,\boldsymbol{y}_n)^T \) and \( \theta = (\theta_0, \theta_1)^T \)

    + +

    It is convenient to write \( \mathbf{\boldsymbol{y}} = X\theta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by (we keep the intercept here)

    +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ + +

    The cost/loss/risk function is given by (

    +$$ +C(\theta) = \frac{1}{n}||X\theta-\mathbf{y}||_{2}^{2} = \frac{1}{n}\sum_{i=1}^{100}\left[ (\theta_0 + \theta_1 x_i)^2 - 2 y_i (\theta_0 + \theta_1 x_i) + y_i^2\right] +$$ + +

    and we want to find \( \theta \) such that \( C(\theta) \) is minimized.

    + +









    +

    The derivative of the cost/loss function

    + +

    Computing \( \partial C(\theta) / \partial \theta_0 \) and \( \partial C(\theta) / \partial \theta_1 \) we can show that the gradient can be written as

    +$$ +\nabla_{\theta} C(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = \frac{2}{n}X^T(X\theta - \mathbf{y}), +$$ + +

    where \( X \) is the design matrix defined above.

    + +









    +

    The Hessian matrix

    +

    The Hessian matrix of \( C(\theta) \) is given by

    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X. +$$ + +

    This result implies that \( C(\theta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite.

    + +









    +

    Simple program

    + +

    We can now write a program that minimizes \( C(\theta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to

    +$$ +\theta_{k+1} = \theta_k - \gamma \nabla_\theta C(\theta_k), \ k=0,1,\cdots +$$ + +

    We can use the expression we computed for the gradient and let use a +\( \theta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\theta C(\theta_k) || \leq \epsilon = 10^{-8} \). Note that the code below does not include the latter stop criterion. +

    + +

    And finally we can compare our solution for \( \theta \) with the analytic result given by +\( \theta= (X^TX)^{-1} X^T \mathbf{y} \). +

    + +









    +

    Gradient Descent Example

    + +

    Here our simple example

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +# Hessian matrix
    +H = (2.0/n)* X.T @ X
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y
    +print(theta_linreg)
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +for iter in range(Niterations):
    +    gradient = (2.0/n)*X.T @ (X @ theta-y)
    +    theta -= eta*gradient
    +
    +print(theta)
    +xnew = np.array([[0],[2]])
    +xbnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = xbnew.dot(theta)
    +ypredict2 = xbnew.dot(theta_linreg)
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Gradient descent and Ridge

    + +

    We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \theta \),

    +$$ +C_{\text{ridge}}(\theta) = \frac{1}{n}||X\theta -\mathbf{y}||^2 + \lambda ||\theta||^2, \ \lambda \geq 0. +$$ + +

    In order to minimize \( C_{\text{ridge}}(\theta) \) using GD we adjust the gradient as follows

    +$$ +\nabla_\theta C_{\text{ridge}}(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \theta_0 \\ \theta_1\end{bmatrix} = 2 (\frac{1}{n}X^T(X\theta - \mathbf{y})+\lambda \theta). +$$ + +

    We can easily extend our program to minimize \( C_{\text{ridge}}(\theta) \) using gradient descent and compare with the analytical solution given by

    +$$ +\theta_{\text{ridge}} = \left(X^T X + n\lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ + + +









    +

    The Hessian matrix for Ridge Regression

    +

    The Hessian matrix of Ridge Regression for our simple example is given by

    +$$ +\boldsymbol{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X+2\lambda\boldsymbol{I}. +$$ + +

    This implies that the Hessian matrix is positive definite, hence the stationary point is a +minimum. +Note that the Ridge cost function is convex being a sum of two convex +functions. Therefore, the stationary point is a global +minimum of this function. +

    + +









    +

    Program example for gradient descent with Ridge Regression

    + + +
    +
    +
    +
    +
    +
    from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.mplot3d import Axes3D
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import sys
    +
    +# the number of datapoints
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +
    +#Ridge parameter lambda
    +lmbda  = 0.001
    +Id = n*lmbda* np.eye(XT_X.shape[0])
    +
    +# Hessian matrix
    +H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])
    +# Get the eigenvalues
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +
    +theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y
    +print(theta_linreg)
    +# Start plain gradient descent
    +theta = np.random.randn(2,1)
    +
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta
    +    theta -= eta*gradients
    +
    +print(theta)
    +ypredict = X @ theta
    +ypredict2 = X @ theta_linreg
    +plt.plot(x, ypredict, "r-")
    +plt.plot(x, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Gradient descent example for Ridge')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Using gradient descent methods, limitations

    + +
      +
    • Gradient descent (GD) finds local minima of our function. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
    • +
    • GD is sensitive to initial conditions. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
    • +
    • Gradients are computationally expensive to calculate for large datasets. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, \( E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2 \); for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over all \( n \) data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called "mini batches". This has the added benefit of introducing stochasticity into our algorithm.
    • +
    • GD is very sensitive to choices of learning rates. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would adaptively choose the learning rates to match the landscape.
    • +
    • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
    • +
    • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
    • +
    +









    +

    Improving gradient descent with momentum

    + +

    We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent.

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# take a step
    +		solution = solution - step_size * gradient
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# perform the gradient descent search
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + + +
    +
    +
    +
    +
    +
    from numpy import asarray
    +from numpy import arange
    +from numpy.random import rand
    +from numpy.random import seed
    +from matplotlib import pyplot
    + 
    +# objective function
    +def objective(x):
    +	return x**2.0
    + 
    +# derivative of objective function
    +def derivative(x):
    +	return x * 2.0
    + 
    +# gradient descent algorithm
    +def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):
    +	# track all solutions
    +	solutions, scores = list(), list()
    +	# generate an initial point
    +	solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
    +	# keep track of the change
    +	change = 0.0
    +	# run the gradient descent
    +	for i in range(n_iter):
    +		# calculate gradient
    +		gradient = derivative(solution)
    +		# calculate update
    +		new_change = step_size * gradient + momentum * change
    +		# take a step
    +		solution = solution - new_change
    +		# save the change
    +		change = new_change
    +		# evaluate candidate point
    +		solution_eval = objective(solution)
    +		# store solution
    +		solutions.append(solution)
    +		scores.append(solution_eval)
    +		# report progress
    +		print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
    +	return [solutions, scores]
    + 
    +# seed the pseudo random number generator
    +seed(4)
    +# define range for input
    +bounds = asarray([[-1.0, 1.0]])
    +# define the total iterations
    +n_iter = 30
    +# define the step size
    +step_size = 0.1
    +# define momentum
    +momentum = 0.3
    +# perform the gradient descent search with momentum
    +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)
    +# sample input range uniformly at 0.1 increments
    +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
    +# compute targets
    +results = objective(inputs)
    +# create a line plot of input vs result
    +pyplot.plot(inputs, results)
    +# plot the solutions found
    +pyplot.plot(solutions, scores, '.-', color='red')
    +# show the plot
    +pyplot.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Overview video on Stochastic Gradient Descent

    + +What is Stochastic Gradient Descent + +









    +

    Batches and mini-batches

    + +

    In gradient descent we compute the cost function and its gradient for all data points we have.

    + +

    In large-scale applications such as the ILSVRC challenge, the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. +

    + +









    +

    Stochastic Gradient Descent (SGD)

    + +

    In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. +

    + +

    This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. +

    + +

    In our notes with SGD we mean stochastic gradient descent with mini-batches.

    + +









    +

    Stochastic Gradient Descent

    + +

    Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. +

    + +

    The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

    +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + + +









    +

    Computation of gradients

    + +

    This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

    +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

    Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

    + +









    +

    SGD example

    +

    As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). +

    + +

    The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

    +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + + +









    +

    The gradient step

    + +

    Thus a gradient descent step now looks like

    +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

    where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

    + +









    +

    Simple example code

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 10 #number of epochs
    +
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for 
    +        j += 1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

    + +









    +

    When do we stop?

    + +

    A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

    + +









    +

    Slightly different approach

    + +

    Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. Such approaches are +also called scaling. There are many such ways to scale the learning +rate +and discussions here. See +also +https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1 +for a discussion of different scaling functions for the learning rate. +

    + +









    +

    Time decay rate

    + +

    As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \).

    + +

    In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np 
    +
    +def step_length(t,t0,t1):
    +    return t0/(t+t1)
    +
    +n = 100 #100 datapoints 
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +n_epochs = 500 #number of epochs
    +t0 = 1.0
    +t1 = 10
    +
    +gamma_j = t0/t1
    +j = 0
    +for epoch in range(1,n_epochs+1):
    +    for i in range(m):
    +        k = np.random.randint(m) #Pick the k-th minibatch at random
    +        #Compute the gradient using the data in minibatch Bk
    +        #Compute new suggestion for beta
    +        t = epoch*m+i
    +        gamma_j = step_length(t,t0,t1)
    +        j += 1
    +
    +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Code with a Number of Minibatches which varies

    + +

    In the code here we vary the number of mini-batches.

    + + +
    +
    +
    +
    +
    +
    # Importing various packages
    +from math import exp, sqrt
    +from random import random, seed
    +import numpy as np
    +import matplotlib.pyplot as plt
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +
    +for iter in range(Niterations):
    +    gradients = 2.0/n*X.T @ ((X @ theta)-y)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Replace or not

    + +

    In the above code, we have use replacement in setting up the +mini-batches. The discussion +here may be +useful. +

    + +









    +

    Momentum based GD

    + +

    The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows +

    + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\label{_auto1} +\end{align} +$$ + +

    where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is +

    + +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +

    where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \).

    + +









    +

    More on momentum based approaches

    + +

    Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by +

    + +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ + +

    We can discretize this equation in the usual way to get

    + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

    Rearranging this equation, we can rewrite this as

    + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ + + +









    +

    Momentum parameter

    + +

    Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: +

    + +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ + +

    Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). +

    + +

    Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. +

    + +

    These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). +

    + +

    In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule +

    + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\label{_auto2} +\end{align} +$$ + +

    One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \).

    + +









    +

    Second moment of the gradient

    + +

    In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. +

    + +

    Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and +ADAM. +

    + +









    +

    RMS prop

    + +

    In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by +

    + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

    where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. +

    + +









    +

    ADAM optimizer

    + +

    A related algorithm is the ADAM optimizer. In +ADAM, we keep a running average of +both the first and second moment of the gradient and use this +information to adaptively change the learning rate for different +parameters. The method isefficient when working with large +problems involving lots data and/or parameters. It is a combination of the +gradient descent with momentum algorithm and the RMSprop algorithm +discussed above. +

    + +

    In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) +

    + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\boldsymbol{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \boldsymbol{\mathbf{m}}_t \over \sqrt{\boldsymbol{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\label{_auto5} +\end{align} +$$ + +

    where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. +

    + +

    Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \boldsymbol{\mathbf{s}}_t - +(\boldsymbol{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by +

    + +$$ +\Delta \theta_{t+1}= -\eta_t { \boldsymbol{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + + +









    +

    Algorithms and codes for Adagrad, RMSprop and Adam

    + +

    The algorithms we have implemented are well described in the text by Goodfellow, Bengio and Courville, chapter 8.

    + +

    The codes which implement these algorithms are discussed below here.

    + +









    +

    Practical tips

    + +
      +
    • Randomize the data when making mini-batches. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
    • +
    • Transform your inputs. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
    • +
    • Monitor the out-of-sample performance. Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This early stopping significantly improves performance in many settings.
    • +
    • Adaptive optimization methods don't always have good generalization. Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
    • +
    +









    +

    Sneaking in automatic differentiation using Autograd

    + +

    We anticipate our discussions to come in connection with neural networks and automatic differentiation +by showing how we can use autograd for the cases above. Later we will replace autograd with JAX. +

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients for OLS
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x#+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 30
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(theta)
    +    theta -= eta*gradients
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd")
    +print(theta)
    +
    +# Now improve with momentum gradient descent
    +change = 0.0
    +delta_momentum = 0.3
    +for iter in range(Niterations):
    +    # calculate gradient
    +    gradients = training_gradient(theta)
    +    # calculate update
    +    new_change = eta*gradients+delta_momentum*change
    +    # take a step
    +    theta -= new_change
    +    # save the change
    +    change = new_change
    +    print(iter,gradients[0],gradients[1])
    +print("theta from own gd wth momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    But none of these can compete with Newton's method

    + + + +
    +
    +
    +
    +
    +
    # Using Newton's method
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +def CostOLS(beta):
    +    return (1.0/n)*np.sum((y-X @ beta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(beta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +# Note that here the Hessian does not depend on the parameters beta
    +invH = np.linalg.pinv(H)
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +beta = np.random.randn(2,1)
    +Niterations = 5
    +
    +# define the gradient
    +training_gradient = grad(CostOLS)
    +
    +for iter in range(Niterations):
    +    gradients = training_gradient(beta)
    +    beta -= invH @ gradients
    +    print(iter,gradients[0],gradients[1])
    +print("beta from own Newton code")
    +print(beta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Including Stochastic Gradient Descent with Autograd

    +

    In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using autograd.

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 1000
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +xnew = np.array([[0],[2]])
    +Xnew = np.c_[np.ones((2,1)), xnew]
    +ypredict = Xnew.dot(theta)
    +ypredict2 = Xnew.dot(theta_linreg)
    +
    +plt.plot(xnew, ypredict, "r-")
    +plt.plot(xnew, ypredict2, "b-")
    +plt.plot(x, y ,'ro')
    +plt.axis([0,2.0,0, 15.0])
    +plt.xlabel(r'$x$')
    +plt.ylabel(r'$y$')
    +plt.title(r'Random numbers ')
    +plt.show()
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +for epoch in range(n_epochs):
    +# Can you figure out a better way of setting up the contributions to each batch?
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        theta = theta - eta*gradients
    +print("theta from own sdg")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Same code but now with momentum gradient descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using SGD
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 100
    +x = 2*np.random.rand(n,1)
    +y = 4+3*x+np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +# Hessian matrix
    +H = (2.0/n)* XT_X
    +EigValues, EigVectors = np.linalg.eig(H)
    +print(f"Eigenvalues of Hessian Matrix:{EigValues}")
    +
    +theta = np.random.randn(2,1)
    +eta = 1.0/np.max(EigValues)
    +Niterations = 100
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +
    +for iter in range(Niterations):
    +    gradients = (1.0/n)*training_gradient(y, X, theta)
    +    theta -= eta*gradients
    +print("theta from own gd")
    +print(theta)
    +
    +
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +t0, t1 = 5, 50
    +def learning_schedule(t):
    +    return t0/(t+t1)
    +
    +theta = np.random.randn(2,1)
    +
    +change = 0.0
    +delta_momentum = 0.3
    +
    +for epoch in range(n_epochs):
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        eta = learning_schedule(epoch*m+i)
    +        # calculate update
    +        new_change = eta*gradients+delta_momentum*change
    +        # take a step
    +        theta -= new_change
    +        # save the change
    +        change = new_change
    +print("theta from own sdg with momentum")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Similar (second order function now) problem but now with AdaGrad

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        Giter += gradients*gradients
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +        theta -= update
    +print("theta from own AdaGrad")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Running this code we note an almost perfect agreement with the results from matrix inversion.

    + +









    +

    RMSprop for adaptive learning rate with Stochastic Gradient Descent

    + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameter rho
    +rho = 0.99
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-8
    +for epoch in range(n_epochs):
    +    Giter = 0.0
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +	# Accumulated gradient
    +	# Scaling with rho the new and the previous results
    +        Giter = (rho*Giter+(1-rho)*gradients*gradients)
    +	# Taking the diagonal only and inverting
    +        update = gradients*eta/(delta+np.sqrt(Giter))
    +	# Hadamard product
    +        theta -= update
    +print("theta from own RMSprop")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    And finally ADAM

    + + + +
    +
    +
    +
    +
    +
    # Using Autograd to calculate gradients using RMSprop  and Stochastic Gradient descent
    +# OLS example
    +from random import random, seed
    +import numpy as np
    +import autograd.numpy as np
    +import matplotlib.pyplot as plt
    +from autograd import grad
    +
    +# Note change from previous example
    +def CostOLS(y,X,theta):
    +    return np.sum((y-X @ theta)**2)
    +
    +n = 1000
    +x = np.random.rand(n,1)
    +y = 2.0+3*x +4*x*x# +np.random.randn(n,1)
    +
    +X = np.c_[np.ones((n,1)), x, x*x]
    +XT_X = X.T @ X
    +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
    +print("Own inversion")
    +print(theta_linreg)
    +
    +
    +# Note that we request the derivative wrt third argument (theta, 2 here)
    +training_gradient = grad(CostOLS,2)
    +# Define parameters for Stochastic Gradient Descent
    +n_epochs = 50
    +M = 5   #size of each minibatch
    +m = int(n/M) #number of minibatches
    +# Guess for unknown parameters theta
    +theta = np.random.randn(3,1)
    +
    +# Value for learning rate
    +eta = 0.01
    +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980
    +beta1 = 0.9
    +beta2 = 0.999
    +# Including AdaGrad parameter to avoid possible division by zero
    +delta  = 1e-7
    +iter = 0
    +for epoch in range(n_epochs):
    +    first_moment = 0.0
    +    second_moment = 0.0
    +    iter += 1
    +    for i in range(m):
    +        random_index = M*np.random.randint(m)
    +        xi = X[random_index:random_index+M]
    +        yi = y[random_index:random_index+M]
    +        gradients = (1.0/M)*training_gradient(yi, xi, theta)
    +        # Computing moments first
    +        first_moment = beta1*first_moment + (1-beta1)*gradients
    +        second_moment = beta2*second_moment+(1-beta2)*gradients*gradients
    +        first_term = first_moment/(1.0-beta1**iter)
    +        second_term = second_moment/(1.0-beta2**iter)
    +	# Scaling with rho the new and the previous results
    +        update = eta*first_term/(np.sqrt(second_term)+delta)
    +        theta -= update
    +print("theta from own ADAM")
    +print(theta)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Material for the lab sessions

    Material for the lab sessions on Tuesday and Wednesday

    +

      +
    1. Exercise set for week 37
    2. +
    3. Work on project 1 +
      • -
      • Calculations of expectation values
      • -
      • Discussion of resampling techniques
      • -
      • Exercise set for week 37
      • -
      • Work on project 1
      • -
      • Video of exercise sessions week 37
      • For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.
      +
    - -









    -

    Material for lecture Monday September 9

    - -









    -

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

    Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.

    - -









    -

    More basic Statistics and Bayes' theorem

    - -

    A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. -

    - -

    Assume we have two domains of events \( X=[x_0,x_1,\dots,x_{n-1}] \) and \( Y=[y_0,y_1,\dots,y_{n-1}] \).

    - -

    We define also the likelihood for \( X \) and \( Y \) as \( p(X) \) and \( p(Y) \) respectively. -The likelihood of a specific event \( x_i \) (or \( y_i \)) is then written as \( p(X=x_i) \) or just \( p(x_i)=p_i \). -

    - -
    -Union of events is given by -

    -$$ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -$$ -

    - - -
    -The product rule (aka joint probability) is given by -

    -$$ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -$$ - -

    where we read \( p(X\vert Y) \) as the likelihood of obtaining \( X \) given \( Y \).

    -
    - - -

    If we have independent events then \( p(X,Y)=p(X)p(Y) \).

    - -









    -

    Marginal Probability

    - -

    The marginal probability is defined in terms of only one of the set of variables \( X,Y \). For a discrete probability we have

    -
    - -

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

    - - -









    -

    Conditional Probability

    - -

    The conditional probability, if \( p(Y) > 0 \), is

    -
    - -

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

    - - -









    -

    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.

    - -

    Let us try to illustrate Bayes' theorem through an example.

    - -









    -

    Example of Usage of Bayes' theorem

    - -

    Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable \( X \). It takes binary -values with \( X=1 \) representing a positive event and \( X=0 \) being a -negative event. We reserve \( Y \) as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). -

    - -

    We let \( Y=1 \) represent the the case of having breast cancer and \( Y=0 \) as not.

    - -

    Let us assume that if you have breast cancer, the test will be positive with a probability of \( 0.8 \), that is we have

    - -$$ -p(X=1\vert Y=1) =0.8. -$$ - -

    This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \( 80\% \) for having cancer. -It is however not correct, as the following Bayesian analysis shows. -

    - -









    -

    Doing it correctly

    - -

    If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is -

    - -$$ -p(Y=1) =0.004. -$$ - -

    We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have

    -$$ -p(X=1\vert Y=0) =0.1. -$$ - -

    Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute

    - -$$ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -$$ - -

    That is, in case of a positive test, there is only a \( 3\% \) chance of having breast cancer!

    - -









    -

    Bayes' Theorem and Ridge and Lasso Regression

    - -

    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: 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 \( \mathbb{E}[x_i] \). Each mean value \( \mathbb{E}[x_i] \) -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 \( \mathbb{E}[x_i]=x_i \) in the discussion -which follows. We do the same for \( \mathbb{E}[z]=z \). -

    - -

    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 central limit theorem leads 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 (the so-called Bessel correction) -

    -$$ - \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. Keep -in mind that we have assumed that the variables \( x \) are independent -and identically distributed. This is obviously not always the -case. For example, the random numbers (or better pseudorandom numbers) -we generate in various calculations do always exhibit some -correlations. -

    - -

    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 form /analytic expression for -\( \tilde{p}(x) \). -

    - -









    -

    Confidence Intervals

    - -

    Confidence intervals are used in statistics and represent 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. -

    - -

    In the exercises this week we show 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 can 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. -

    - -









    -

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

    - - - -
    -
    -
    -
    -
    -
    import numpy as np
    -from time import time
    -from scipy.stats import norm
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples 
    -# Bootstrap algorithm
    -def bootstrap(data, datapoints):
    -    t = np.zeros(datapoints)
    -    n = len(data)
    -    # non-parametric bootstrap         
    -    for i in range(datapoints):
    -        t[i] = np.mean(data[np.random.randint(0,n,n)])
    -    # analysis    
    -    print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))
    -    return t
    -
    -# We set the mean value to 100 and the standard deviation to 15
    -mu, sigma = 100, 15
    -datapoints = 10000
    -# We generate random numbers according to the normal distribution
    -x = mu + sigma*np.random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, 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 (normalized data if density = True)
    -n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)
    -# add a 'best fit' line  
    -y = norm.pdf(binsboot, np.mean(t), np.std(t))
    -lt = plt.plot(binsboot, y, 'b', linewidth=1)
    -plt.xlabel('x')
    -plt.ylabel('Probability')
    -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{D} \) consisting of the data -\( \mathbf{X}_\mathcal{D}=\{(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

    - -

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

    - -









    -

    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=False).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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Note that we kept the intercept column in the fitting here. This means that we need to set the intercept in the call to the Scikit-Learn function as False. Alternatively, we could have set up the design matrix \( X \) without the first column of ones.

    - - -

    The same example but now with cross-validation

    - -

    In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error.

    - - -
    -
    -
    -
    -
    -
    # 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(fit_intercept=False)
    -# 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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Material for the lab sessions

    - - -

    Linking the regression analysis with a statistical interpretation

    - -

    We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -\( \beta \). -

    - -

    The -advantage of doing linear regression is that we actually end up with -analytical expressions for several statistical quantities. -Standard least squares and Ridge regression allow us to -derive quantities like the variance and other expectation values in a -rather straightforward way. -

    - -

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

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

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

    - -

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

    - -









    -

    Assumptions made

    - -

    The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) -that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) -which describe our data -

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

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

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









    -

    Expectation value and variance

    - -

    We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)

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

    while -its variance is -

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

    Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with -mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). -

    - -









    -

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

    - -

    With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value

    -$$ -\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. -$$ - -

    This means that the estimator of the regression parameters is unbiased.

    - -

    We can also calculate the variance

    - -

    The variance of the optimal value \( \boldsymbol{\hat{\beta}} \) is

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

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

    - -

    In a similar way, we can obtain analytical expressions for say the -expectation values of the parameters \( \boldsymbol{\beta} \) and their variance -when we employ Ridge regression, allowing us again to define a confidence interval. -

    - -

    It is rather straightforward to show that

    -$$ -\mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}. -$$ - -

    We see clearly that -\( \mathbb{E} \big[ \hat{\boldsymbol{\beta}}^{\mathrm{Ridge}} \big] \not= \hat{\boldsymbol{\beta}}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). -

    - -

    We can also compute the variance as

    - -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, -$$ - -

    and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.

    - -

    With this, we can compute the difference

    - -$$ -\mbox{Var}[\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}]-\mbox{Var}(\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. -$$ - -

    The difference is non-negative definite since each component of the -matrix product is non-negative definite. -This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. -

    - -

    For more discussions of Ridge regression and calculation of averages, Wessel van Wieringen's article is highly recommended.

    -
    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz index 7e1990ba9..3a4cefdc6 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 0aba405c9..c40ec2419 100644 --- a/doc/pub/week37/ipynb/week37.ipynb +++ b/doc/pub/week37/ipynb/week37.ipynb @@ -2,8 +2,10 @@ "cells": [ { "cell_type": "markdown", - "id": "7ce0c2c8", - "metadata": {}, + "id": "ebae0536", + "metadata": { + "editable": true + }, "source": [ "\n", @@ -12,2669 +14,2431 @@ }, { "cell_type": "markdown", - "id": "3bd9c0ba", - "metadata": {}, + "id": "c87edf63", + "metadata": { + "editable": true + }, "source": [ "# Week 37: Statistical interpretations and Resampling Methods\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", "\n", - "Date: **September 9, 2024**\n", + "Date: **September 8-12, 2025**\n", "\n", "" ] }, { "cell_type": "markdown", - "id": "be6135df", - "metadata": {}, + "id": "9b6436c9", + "metadata": { + "editable": true + }, "source": [ "## Plans for week 37, lecture Monday\n", "\n", - "**Material for the lecture on Monday September 9.**\n", + "**Plans and material for the lecture on Monday September 8.**\n", "\n", - " * [Video of Lecture](https://youtu.be/omLmp_kkie0)\n", + "The family of gradient descent methods\n", + "1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge\n", "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember9.pdf)\n", + "2. Improving gradient descent with momentum\n", "\n", - " * Statistical interpretation of Ridge and Lasso regression, see also slides from last week\n", + "3. Introducing stochastic gradient descent\n", "\n", - " * Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.\n", - "\n", - " * Readings and Videos:\n", - " * Raschka et al, pages 175-192\n", - "\n", - " * Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). See .\n", - "\n", - " * [Video on cross validation](https://www.youtube.com/watch?v=fSytzGwwBVw)\n", - "\n", - " * [Video on Bootstrapping](https://www.youtube.com/watch?v=Xz0x-8-cgaQ)\n", - "\n", - " * [Video on bias-variance tradeoff](https://www.youtube.com/watch?v=EuBBz3bI-aA)" - ] - }, - { - "cell_type": "markdown", - "id": "3ac97fd3", - "metadata": {}, - "source": [ - "## Plans for week 37, lab sessions\n", - "\n", - "**Material for the lab sessions on Tuesday and Wednesday.**\n", - "\n", - " * Calculations of expectation values\n", - "\n", - " * Discussion of resampling techniques\n", - "\n", - " * Exercise set for week 37\n", - "\n", - " * Work on project 1\n", - "\n", - " * [Video of exercise sessions week 37](https://youtu.be/bK4AEcTu-oM)\n", - "\n", - " * For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended." - ] - }, - { - "cell_type": "markdown", - "id": "7010206d", - "metadata": {}, - "source": [ - "## Material for lecture Monday September 9" - ] - }, - { - "cell_type": "markdown", - "id": "2467ccb1", - "metadata": {}, - "source": [ - "## 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", - "id": "4e2b9f77", - "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", - "id": "aa3e18f2", - "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", - "id": "a9836e09", - "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", - "id": "81c40e6c", - "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", - "id": "fd6babf0", - "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", - "id": "71dfe09f", - "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", - "id": "90f49395", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eb1d8923", - "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", - "id": "a3b37065", - "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", - "id": "092a8fe2", - "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}$." - ] - }, - { - "cell_type": "markdown", - "id": "f15ab83a", - "metadata": {}, - "source": [ - "## 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", - "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", - "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." - ] - }, - { - "cell_type": "markdown", - "id": "5ed97aa3", - "metadata": {}, - "source": [ - "## 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", - "id": "7b570c43", - "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", - "id": "8a82d943", - "metadata": {}, - "source": [ - "which becomes" - ] - }, - { - "cell_type": "markdown", - "id": "a9fe176c", - "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", - "id": "720c650c", - "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", - "id": "4c13afe3", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f23aa0de", - "metadata": {}, - "source": [ - "which leads to the well-known OLS equation for the optimal paramters $\\beta$" - ] - }, - { - "cell_type": "markdown", - "id": "cc0ec7c0", - "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", - "id": "71275e73", - "metadata": {}, - "source": [ - "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics." - ] - }, - { - "cell_type": "markdown", - "id": "4c41ecf0", - "metadata": {}, - "source": [ - "## More basic Statistics and Bayes' theorem\n", - "\n", - "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n", - "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n", - "\n", - "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n", - "\n", - "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n", - "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n", - "\n", - "**Union of events is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "890ba6f9", - "metadata": {}, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dfcd3bf6", - "metadata": {}, - "source": [ - "**The product rule (aka joint probability) is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "956837e7", - "metadata": {}, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d3802c8c", - "metadata": {}, - "source": [ - "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n", - "\n", - "If we have independent events then $p(X,Y)=p(X)p(Y)$." - ] - }, - { - "cell_type": "markdown", - "id": "95db199e", - "metadata": {}, - "source": [ - "## Marginal Probability\n", - "\n", - "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have" - ] - }, - { - "cell_type": "markdown", - "id": "57fb6f6a", - "metadata": {}, - "source": [ - "$$\n", - "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ea33fe6b", - "metadata": {}, - "source": [ - "## Conditional Probability\n", - "\n", - "The conditional probability, if $p(Y) > 0$, is" - ] - }, - { - "cell_type": "markdown", - "id": "5705568f", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ef0bee11", - "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", - "id": "7569074e", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3cecb6a2", - "metadata": {}, - "source": [ - "which we can rewrite as" - ] - }, - { - "cell_type": "markdown", - "id": "c76a1bc7", - "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", - "id": "d97f5c86", - "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$." - ] - }, - { - "cell_type": "markdown", - "id": "6e5646ae", - "metadata": {}, - "source": [ - "## 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", - "Let us try to illustrate Bayes' theorem through an example." - ] - }, - { - "cell_type": "markdown", - "id": "3a23e77a", - "metadata": {}, - "source": [ - "## Example of Usage of Bayes' theorem\n", - "\n", - "Let us suppose that you are undergoing a series of mammography scans in\n", - "order to rule out possible breast cancer cases. We define the\n", - "sensitivity for a positive event by the variable $X$. It takes binary\n", - "values with $X=1$ representing a positive event and $X=0$ being a\n", - "negative event. We reserve $Y$ as a classification parameter for\n", - "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n", - "\n", - "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n", - "\n", - "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "7432af91", - "metadata": {}, - "source": [ - "$$\n", - "p(X=1\\vert Y=1) =0.8.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ea23569c", - "metadata": {}, - "source": [ - "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n", - "It is however not correct, as the following Bayesian analysis shows." - ] - }, - { - "cell_type": "markdown", - "id": "18e40c37", - "metadata": {}, - "source": [ - "## Doing it correctly\n", - "\n", - "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n", - "Let us assume that the prior probability in the population as a whole is" - ] - }, - { - "cell_type": "markdown", - "id": "5c32a5c2", - "metadata": {}, - "source": [ - "$$\n", - "p(Y=1) =0.004.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b84fb7fb", - "metadata": {}, - "source": [ - "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have" - ] - }, - { - "cell_type": "markdown", - "id": "2c3b605b", - "metadata": {}, - "source": [ - "$$\n", - "p(X=1\\vert Y=0) =0.1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d05ca03a", - "metadata": {}, - "source": [ - "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute" - ] - }, - { - "cell_type": "markdown", - "id": "4f4cee49", - "metadata": {}, - "source": [ - "$$\n", - "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4176d701", - "metadata": {}, - "source": [ - "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!" - ] - }, - { - "cell_type": "markdown", - "id": "5ad8813c", - "metadata": {}, - "source": [ - "## Bayes' Theorem and Ridge and Lasso Regression\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", - "id": "450006d9", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1b2173c5", - "metadata": {}, - "source": [ - "is given by" - ] - }, - { - "cell_type": "markdown", - "id": "10b2d8ce", - "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", - "id": "a18147f9", - "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", - "id": "3214dac3", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bd650eeb", - "metadata": {}, - "source": [ - "Bayes' theorem comes to our rescue here since (omitting the normalization constant)" - ] - }, - { - "cell_type": "markdown", - "id": "08d630ed", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "582ebf85", - "metadata": {}, - "source": [ - "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta})$!" - ] - }, - { - "cell_type": "markdown", - "id": "1a53c784", - "metadata": {}, - "source": [ - "## 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", - "id": "89f8d622", - "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", - "id": "f1138958", - "metadata": {}, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "c4b8fdc1", - "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", - "id": "0e65c2b7", - "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", - "id": "4f7bc40c", - "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", - "id": "f1c44499", - "metadata": {}, - "source": [ - "and replacing $1/2\\tau^2$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "215c872a", - "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", - "id": "a248bb79", - "metadata": {}, - "source": [ - "which is our Ridge cost function! Nice, isn't it?" - ] - }, - { - "cell_type": "markdown", - "id": "bdc951a2", - "metadata": {}, - "source": [ - "## 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", - "id": "ce54b5ff", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a158d0d6", - "metadata": {}, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "b1010f4a", - "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", - "id": "48b806e1", - "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", - "id": "4e3090e9", - "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", - "id": "af23d3a1", - "metadata": {}, - "source": [ - "and replacing $1/\\tau$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "72d5f20a", - "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", - "id": "45d3140f", - "metadata": {}, - "source": [ - "which is our Lasso cost function!" - ] - }, - { - "cell_type": "markdown", - "id": "6c40d9a0", - "metadata": {}, - "source": [ - "## 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)." - ] - }, - { - "cell_type": "markdown", - "id": "bc0ed879", - "metadata": {}, - "source": [ - "## 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." - ] - }, - { - "cell_type": "markdown", - "id": "a2f50278", - "metadata": {}, - "source": [ - "## 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." - ] - }, - { - "cell_type": "markdown", - "id": "d05b795a", - "metadata": {}, - "source": [ - "## Why resampling methods ?\n", - "**Statistical analysis.**\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." - ] - }, - { - "cell_type": "markdown", - "id": "61291aec", - "metadata": {}, - "source": [ - "## 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", - "* 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." - ] - }, - { - "cell_type": "markdown", - "id": "e0053e66", - "metadata": {}, - "source": [ - "## 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." - ] - }, - { - "cell_type": "markdown", - "id": "5bc0cc49", - "metadata": {}, - "source": [ - "## Resampling methods: Bootstrap\n", - "Bootstrapping is a [non-parametric approach](https://en.wikipedia.org/wiki/Nonparametric_statistics) 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", - "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", - "Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called **central limit theorem**." - ] - }, - { - "cell_type": "markdown", - "id": "61de3a3e", - "metadata": {}, - "source": [ - "## The Central Limit Theorem\n", - "\n", - "Suppose we have a PDF $p(x)$ from which we generate a series $N$\n", - "of averages $\\mathbb{E}[x_i]$. Each mean value $\\mathbb{E}[x_i]$\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 $\\mathbb{E}[x_i]=x_i$ in the discussion\n", - "which follows. We do the same for $\\mathbb{E}[z]=z$.\n", - "\n", - "If we compute the mean $z$ of $m$ such mean values $x_i$" - ] - }, - { - "cell_type": "markdown", - "id": "45c40645", - "metadata": {}, - "source": [ - "$$\n", - "z=\\frac{x_1+x_2+\\dots+x_m}{m},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f96414b9", - "metadata": {}, - "source": [ - "the question we pose is which is the PDF of the new variable $z$." - ] - }, - { - "cell_type": "markdown", - "id": "89324724", - "metadata": {}, - "source": [ - "## 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", - "id": "c7dc04c2", - "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", - "id": "451e8d96", - "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." - ] - }, - { - "cell_type": "markdown", - "id": "b857136e", - "metadata": {}, - "source": [ - "## Rewriting the $\\delta$-function\n", - "\n", - "If we use the integral expression for the $\\delta$-function" - ] - }, - { - "cell_type": "markdown", - "id": "81465668", - "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", - "id": "b145c9fd", - "metadata": {}, - "source": [ - "and inserting $e^{i\\mu q-i\\mu q}$ where $\\mu$ is the mean value\n", - "we arrive at" - ] - }, - { - "cell_type": "markdown", - "id": "c2f110e5", - "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", - "id": "9fffd309", - "metadata": {}, - "source": [ - "with the integral over $x$ resulting in" - ] - }, - { - "cell_type": "markdown", - "id": "6d1a1c34", - "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", - "id": "3c425d33", - "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", - "id": "d43d6aa9", - "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", - "id": "b8bd4093", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "id": "b46c892b", - "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", - "id": "0a4fcb69", - "metadata": {}, - "source": [ - "and in the limit $m\\rightarrow \\infty$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "9c6b1478", - "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", - "id": "c179621d", - "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)$." - ] - }, - { - "cell_type": "markdown", - "id": "de489be5", - "metadata": {}, - "source": [ - "## 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 central limit theorem leads to the well-known expression for the\n", - "standard deviation, given by" - ] - }, - { - "cell_type": "markdown", - "id": "43c158c8", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_m=\n", - "\\frac{\\sigma}{\\sqrt{m}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "433141f0", - "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 (the so-called Bessel correction)" - ] - }, - { - "cell_type": "markdown", - "id": "68ffe84c", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_m\\approx \n", - "\\frac{\\sigma}{\\sqrt{m-1}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c685143d", - "metadata": {}, - "source": [ - "In many cases however the above estimate for the standard deviation,\n", - "in particular if correlations are strong, may be too simplistic. Keep\n", - "in mind that we have assumed that the variables $x$ are independent\n", - "and identically distributed. This is obviously not always the\n", - "case. For example, the random numbers (or better pseudorandom numbers)\n", - "we generate in various calculations do always exhibit some\n", - "correlations.\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 form /analytic expression for\n", - "$\\tilde{p}(x)$." - ] - }, - { - "cell_type": "markdown", - "id": "ff2c6f80", - "metadata": {}, - "source": [ - "## Confidence Intervals\n", - "\n", - "Confidence intervals are used in statistics and represent 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", - "In the exercises this week we show 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 can be used to\n", - "construct a confidence interval for the estimates." - ] - }, - { - "cell_type": "markdown", - "id": "de45a804", - "metadata": {}, - "source": [ - "## 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", - "id": "7b76e657", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\mu_{\\beta}\\pm \\frac{z\\sigma_{\\beta}}{\\sqrt{n}}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "68374b3c", - "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." - ] - }, - { - "cell_type": "markdown", - "id": "a33b3849", - "metadata": {}, - "source": [ - "## 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." + "4. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM\n", + "\n", + "" ] }, { "cell_type": "markdown", - "id": "3d4a490b", - "metadata": {}, + "id": "01055296", + "metadata": { + "editable": true + }, "source": [ - "## Resampling methods: More Bootstrap background\n", + "## Readings and Videos:\n", + "1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html\"\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", + "2. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.\n", "\n", - "2. Then using these numbers, we could compute a replica of $\\widehat{\\beta}$ called $\\widehat{\\beta}^*$. \n", + "3. Video on gradient descent at \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})$." + "4. Video on Stochastic gradient descent at " ] }, { "cell_type": "markdown", - "id": "293c5a07", - "metadata": {}, + "id": "5b4c3f44", + "metadata": { + "editable": true + }, "source": [ - "## 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." + "## Material for lecture Monday September 8" ] }, { "cell_type": "markdown", - "id": "21a752e9", - "metadata": {}, + "id": "23544472", + "metadata": { + "editable": true + }, "source": [ - "## Resampling methods: Bootstrap steps\n", - "\n", - "The independent bootstrap works like this: \n", + "## Gradient descent and revisiting Ordinary Least Squares from last week\n", "\n", - "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", + "Last week we started with linear regression as a case study for the gradient descent\n", + "methods. Linear regression is a great test case for the gradient\n", + "descent methods discussed in the lectures since it has several\n", + "desirable properties such as:\n", "\n", - "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", + "1. An analytical solution (recall homework sets for week 35).\n", "\n", - "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\beta}^*$ by evaluating $\\widehat \\beta$ under the observations $\\boldsymbol{x}^*$. \n", + "2. The gradient can be computed analytically.\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^*$." - ] - }, - { - "cell_type": "markdown", - "id": "8409d109", - "metadata": {}, - "source": [ - "## Code example for the Bootstrap method\n", + "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\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." + "We revisit an example similar to what we had in the first homework set. We have a function of the type" ] }, { "cell_type": "code", "execution_count": 1, - "id": "82f5a45c", - "metadata": {}, + "id": "d74adaf2", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "from time import time\n", - "from scipy.stats import norm\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# Returns mean of bootstrap samples \n", - "# Bootstrap algorithm\n", - "def bootstrap(data, datapoints):\n", - " t = np.zeros(datapoints)\n", - " n = len(data)\n", - " # non-parametric bootstrap \n", - " for i in range(datapoints):\n", - " t[i] = np.mean(data[np.random.randint(0,n,n)])\n", - " # analysis \n", - " print(\"Bootstrap Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %8g %14g %15g\" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))\n", - " return t\n", - "\n", - "# We set the mean value to 100 and the standard deviation to 15\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "# We generate random numbers according to the normal distribution\n", - "x = mu + sigma*np.random.randn(datapoints)\n", - "# bootstrap returns the data sample \n", - "t = bootstrap(x, datapoints)" + "x = 2*np.random.rand(m,1)\n", + "y = 4+3*x+np.random.randn(m,1)" ] }, { "cell_type": "markdown", - "id": "b1c292eb", - "metadata": {}, + "id": "fa36c64d", + "metadata": { + "editable": true + }, "source": [ - "We see that our new variance and from that the standard deviation, agrees with the central limit theorem." + "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", + "The linear regression model is given by" ] }, { "cell_type": "markdown", - "id": "19a2ff64", - "metadata": {}, + "id": "571c791d", + "metadata": { + "editable": true + }, "source": [ - "## Plotting the Histogram" + "$$\n", + "h_\\theta(x) = \\boldsymbol{y} = \\theta_0 + \\theta_1 x,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "12d3e9eb", + "metadata": { + "editable": true + }, + "source": [ + "such that" + ] + }, + { + "cell_type": "markdown", + "id": "17610490", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{y}_i = \\theta_0 + \\theta_1 x_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "47fefa69", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient descent example\n", + "\n", + "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\theta = (\\theta_0, \\theta_1)^T$\n", + "\n", + "It is convenient to write $\\mathbf{\\boldsymbol{y}} = X\\theta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by (we keep the intercept here)" + ] + }, + { + "cell_type": "markdown", + "id": "52eb2d30", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "X \\equiv \\begin{bmatrix}\n", + "1 & x_1 \\\\\n", + "\\vdots & \\vdots \\\\\n", + "1 & x_{100} & \\\\\n", + "\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7d89f32b", + "metadata": { + "editable": true + }, + "source": [ + "The cost/loss/risk function is given by (" + ] + }, + { + "cell_type": "markdown", + "id": "5b0fb490", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\theta) = \\frac{1}{n}||X\\theta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\theta_0 + \\theta_1 x_i)^2 - 2 y_i (\\theta_0 + \\theta_1 x_i) + y_i^2\\right]\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "891f388a", + "metadata": { + "editable": true + }, + "source": [ + "and we want to find $\\theta$ such that $C(\\theta)$ is minimized." + ] + }, + { + "cell_type": "markdown", + "id": "d05ffb4b", + "metadata": { + "editable": true + }, + "source": [ + "## The derivative of the cost/loss function\n", + "\n", + "Computing $\\partial C(\\theta) / \\partial \\theta_0$ and $\\partial C(\\theta) / \\partial \\theta_1$ we can show that the gradient can be written as" + ] + }, + { + "cell_type": "markdown", + "id": "f59689ea", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_{\\theta} C(\\theta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\theta_0+\\theta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\theta_0+\\theta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T(X\\theta - \\mathbf{y}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9a119fe4", + "metadata": { + "editable": true + }, + "source": [ + "where $X$ is the design matrix defined above." + ] + }, + { + "cell_type": "markdown", + "id": "ef5c109f", + "metadata": { + "editable": true + }, + "source": [ + "## The Hessian matrix\n", + "The Hessian matrix of $C(\\theta)$ is given by" + ] + }, + { + "cell_type": "markdown", + "id": "5412ed07", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0^2} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} \\\\\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_1^2} & \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T X.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "33c5d9c9", + "metadata": { + "editable": true + }, + "source": [ + "This result implies that $C(\\theta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite." + ] + }, + { + "cell_type": "markdown", + "id": "a8cf7d20", + "metadata": { + "editable": true + }, + "source": [ + "## Simple program\n", + "\n", + "We can now write a program that minimizes $C(\\theta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" + ] + }, + { + "cell_type": "markdown", + "id": "40f0daf3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\theta_{k+1} = \\theta_k - \\gamma \\nabla_\\theta C(\\theta_k), \\ k=0,1,\\cdots\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b09c9d54", + "metadata": { + "editable": true + }, + "source": [ + "We can use the expression we computed for the gradient and let use a\n", + "$\\theta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", + "when $||\\nabla_\\theta C(\\theta_k) || \\leq \\epsilon = 10^{-8}$. **Note that the code below does not include the latter stop criterion**.\n", + "\n", + "And finally we can compare our solution for $\\theta$ with the analytic result given by \n", + "$\\theta= (X^TX)^{-1} X^T \\mathbf{y}$." + ] + }, + { + "cell_type": "markdown", + "id": "081f1192", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient Descent Example\n", + "\n", + "Here our simple example" ] }, { "cell_type": "code", "execution_count": 2, - "id": "0e3146d6", - "metadata": {}, + "id": "5842a0a2", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ - "# the histogram of the bootstrapped data (normalized data if density = True)\n", - "n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)\n", - "# add a 'best fit' line \n", - "y = norm.pdf(binsboot, np.mean(t), np.std(t))\n", - "lt = plt.plot(binsboot, y, 'b', linewidth=1)\n", - "plt.xlabel('x')\n", - "plt.ylabel('Probability')\n", - "plt.grid(True)\n", + "%matplotlib inline\n", + "\n", + "\n", + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", + "\n", + "# the number of datapoints\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "# Hessian matrix\n", + "H = (2.0/n)* X.T @ X\n", + "# Get the eigenvalues\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y\n", + "print(theta_linreg)\n", + "theta = np.random.randn(2,1)\n", + "\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "for iter in range(Niterations):\n", + " gradient = (2.0/n)*X.T @ (X @ theta-y)\n", + " theta -= eta*gradient\n", + "\n", + "print(theta)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(theta)\n", + "ypredict2 = xbnew.dot(theta_linreg)\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "33a2920b", - "metadata": {}, + "id": "923874ba", + "metadata": { + "editable": true + }, "source": [ - "## The bias-variance tradeoff\n", + "## Gradient descent and Ridge\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{D}$ consisting of the data\n", - "$\\mathbf{X}_\\mathcal{D}=\\{(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" + "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\theta$," ] }, { "cell_type": "markdown", - "id": "dcd7d41e", - "metadata": {}, + "id": "442c5abb", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", + "C_{\\text{ridge}}(\\theta) = \\frac{1}{n}||X\\theta -\\mathbf{y}||^2 + \\lambda ||\\theta||^2, \\ \\lambda \\geq 0.\n", "$$" ] }, { "cell_type": "markdown", - "id": "7a13a154", - "metadata": {}, + "id": "743e05ca", + "metadata": { + "editable": true + }, "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" + "In order to minimize $C_{\\text{ridge}}(\\theta)$ using GD we adjust the gradient as follows" ] }, { "cell_type": "markdown", - "id": "12c56a3e", - "metadata": {}, + "id": "27dfced9", + "metadata": { + "editable": true + }, "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", + "\\nabla_\\theta C_{\\text{ridge}}(\\theta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\theta_0+\\theta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\theta_0+\\theta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\theta_0 \\\\ \\theta_1\\end{bmatrix} = 2 (\\frac{1}{n}X^T(X\\theta - \\mathbf{y})+\\lambda \\theta).\n", "$$" ] }, { "cell_type": "markdown", - "id": "ded9dfd0", - "metadata": {}, + "id": "3ff66697", + "metadata": { + "editable": true + }, "source": [ - "We can rewrite this as" + "We can easily extend our program to minimize $C_{\\text{ridge}}(\\theta)$ using gradient descent and compare with the analytical solution given by" ] }, { "cell_type": "markdown", - "id": "5c8be1fb", - "metadata": {}, + "id": "f63f80f9", + "metadata": { + "editable": true + }, "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", + "\\theta_{\\text{ridge}} = \\left(X^T X + n\\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "6ae6d83b", - "metadata": {}, + "id": "dc6a4fff", + "metadata": { + "editable": true + }, "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" + "## The Hessian matrix for Ridge Regression\n", + "The Hessian matrix of Ridge Regression for our simple example is given by" ] }, { "cell_type": "markdown", - "id": "ac6ad12e", - "metadata": {}, + "id": "56a4b43d", + "metadata": { + "editable": true + }, "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", + "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0^2} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} \\\\\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_1^2} & \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T X+2\\lambda\\boldsymbol{I}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "24cd6a77", - "metadata": {}, + "id": "38c6aab3", + "metadata": { + "editable": true + }, "source": [ - "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" + "This implies that the Hessian matrix is positive definite, hence the stationary point is a\n", + "minimum.\n", + "Note that the Ridge cost function is convex being a sum of two convex\n", + "functions. Therefore, the stationary point is a global\n", + "minimum of this function." ] }, { "cell_type": "markdown", - "id": "82580456", - "metadata": {}, + "id": "a4f724c3", + "metadata": { + "editable": true + }, "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", - "id": "542a056a", - "metadata": {}, - "source": [ - "which, using the abovementioned expectation values can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "id": "12d87c8f", - "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", - "id": "661e392d", - "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}$." - ] - }, - { - "cell_type": "markdown", - "id": "c92115cc", - "metadata": {}, - "source": [ - "## A way to Read the Bias-Variance Tradeoff\n", - "\n", - "\n", - "\n", - "\n", - "

    Figure 1:

    \n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "555ecab7", - "metadata": {}, - "source": [ - "## Example code for Bias-Variance tradeoff" + "## Program example for gradient descent with Ridge Regression" ] }, { "cell_type": "code", "execution_count": 3, - "id": "a1e3bf2d", - "metadata": {}, + "id": "ae5d09dc", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ - "import matplotlib.pyplot as plt\n", + "from random import random, seed\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", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", "\n", - "np.random.seed(2018)\n", + "# the number of datapoints\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", "\n", - "n = 500\n", - "n_boostraps = 100\n", - "degree = 18 # A quite high value, just to show.\n", - "noise = 0.1\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\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", + "#Ridge parameter lambda\n", + "lmbda = 0.001\n", + "Id = n*lmbda* np.eye(XT_X.shape[0])\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", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])\n", + "# Get the eigenvalues\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\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", + "theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y\n", + "print(theta_linreg)\n", + "# Start plain gradient descent\n", + "theta = np.random.randn(2,1)\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", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 100\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", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta\n", + " theta -= eta*gradients\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", + "print(theta)\n", + "ypredict = X @ theta\n", + "ypredict2 = X @ theta_linreg\n", + "plt.plot(x, ypredict, \"r-\")\n", + "plt.plot(x, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example for Ridge')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "b05eafde", - "metadata": {}, + "id": "184d283f", + "metadata": { + "editable": true + }, "source": [ - "## Understanding what happens" + "## Using gradient descent methods, limitations\n", + "\n", + "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", + "\n", + "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", + "\n", + "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", + "\n", + "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", + "\n", + "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", + "\n", + "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." + ] + }, + { + "cell_type": "markdown", + "id": "cfb021a5", + "metadata": { + "editable": true + }, + "source": [ + "## Improving gradient descent with momentum\n", + "\n", + "We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent." ] }, { "cell_type": "code", - "execution_count": 1, - "id": "23e711c6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Polynomial degree: 0\n", - "Error: 0.32149601703519115\n", - "Bias^2: 0.3123314713548606\n", - "Var: 0.009164545680330616\n", - "0.32149601703519115 >= 0.3123314713548606 + 0.009164545680330616 = 0.3214960170351912\n", - "Polynomial degree: 1\n", - "Error: 0.08426840630693411\n", - "Bias^2: 0.0796891867672603\n", - "Var: 0.004579219539673834\n", - "0.08426840630693411 >= 0.0796891867672603 + 0.004579219539673834 = 0.08426840630693413\n", - "Polynomial degree: 2\n", - "Error: 0.10398646080125035\n", - "Bias^2: 0.1007711427354898\n", - "Var: 0.0032153180657605116\n", - "0.10398646080125035 >= 0.1007711427354898 + 0.0032153180657605116 = 0.10398646080125032\n", - "Polynomial degree: 3\n", - "Error: 0.06547790180152355\n", - "Bias^2: 0.06208238634231949\n", - "Var: 0.0033955154592040936\n", - "0.06547790180152355 >= 0.06208238634231949 + 0.0033955154592040936 = 0.06547790180152359\n", - "Polynomial degree: 4\n", - "Error: 0.06844519414009445\n", - "Bias^2: 0.06453579006728324\n", - "Var: 0.003909404072811226\n", - "0.06844519414009445 >= 0.06453579006728324 + 0.003909404072811226 = 0.06844519414009446\n", - "Polynomial degree: 5\n", - "Error: 0.05227921801205686\n", - "Bias^2: 0.0481872773043029\n", - "Var: 0.004091940707753939\n", - "0.05227921801205686 >= 0.0481872773043029 + 0.004091940707753939 = 0.052279218012056844\n", - "Polynomial degree: 6\n", - "Error: 0.037813671417389005\n", - "Bias^2: 0.033657685071527665\n", - "Var: 0.00415598634586135\n", - "0.037813671417389005 >= 0.033657685071527665 + 0.00415598634586135 = 0.03781367141738902\n", - "Polynomial degree: 7\n", - "Error: 0.02760977349102253\n", - "Bias^2: 0.022999498260366312\n", - "Var: 0.004610275230656212\n", - "0.02760977349102253 >= 0.022999498260366312 + 0.004610275230656212 = 0.027609773491022525\n", - "Polynomial degree: 8\n", - "Error: 0.017355848195593347\n", - "Bias^2: 0.010331721306655127\n", - "Var: 0.007024126888938232\n", - "0.017355848195593347 >= 0.010331721306655127 + 0.007024126888938232 = 0.01735584819559336\n", - "Polynomial degree: 9\n", - "Error: 0.02660572763718093\n", - "Bias^2: 0.010018312644137363\n", - "Var: 0.016587414993043573\n", - "0.02660572763718093 >= 0.010018312644137363 + 0.016587414993043573 = 0.026605727637180936\n", - "Polynomial degree: 10\n", - "Error: 0.021592704588025025\n", - "Bias^2: 0.010516485576645508\n", - "Var: 0.011076219011379514\n", - "0.021592704588025025 >= 0.010516485576645508 + 0.011076219011379514 = 0.021592704588025022\n", - "Polynomial degree: 11\n", - "Error: 0.07160048164233104\n", - "Bias^2: 0.014436800088904942\n", - "Var: 0.05716368155342608\n", - "0.07160048164233104 >= 0.014436800088904942 + 0.05716368155342608 = 0.07160048164233102\n", - "Polynomial degree: 12\n", - "Error: 0.11547777218872497\n", - "Bias^2: 0.01628578269596628\n", - "Var: 0.09919198949275869\n", - "0.11547777218872497 >= 0.01628578269596628 + 0.09919198949275869 = 0.11547777218872497\n", - "Polynomial degree: 13\n", - "Error: 0.22842468702219465\n", - "Bias^2: 0.01975416527185249\n", - "Var: 0.20867052175034223\n", - "0.22842468702219465 >= 0.01975416527185249 + 0.20867052175034223 = 0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5kyZYrz66KiouYNLRGdwWQm0KgglkIyDpZxZvN9NxEROV6+QY6RDk9972aQnp7OBRdcwK233srjjz9OVFQUq1at4qabbsJqtRIUFMTNN99MWloan332GV999RUzZ87kmWee4c4772yWmrxBowJLTEwMFouF3Nxct+O5ubnEx8cf8XVms5nu3bsDMHDgQLZs2cLMmTMZO3as83W5ubkkJCS4XXPgwIENXs/f3x9/f//GlH5yfPwhvBMUZNLFlEO6Jt6KiHgHk6lRt2U8ae3atW5ff/fdd/To0QOLxeJ2fP369djtdp555hnMZseNkPfff7/e9ZKSkvjzn//Mn//8Z6ZOncrLL7/cpgNLo24J+fn5MWjQIJYsWeI8ZrfbWbJkCcOHDz/u69jtducclJSUFOLj492uWVRUxNq1axt1zWZXswlisjmXTC1tFhGRRsrMzGTKlCls27aNd999lxdeeIG777673nndu3enqqqKF154gV27dvHmm2+yYMECt3MmT57Ml19+ye7du9mwYQNLly6ld+/eLfWjeESjbwlNmTKF66+/nsGDBzN06FDmzp1LaWkpkyZNAuC6666jY8eOzJw5E3DMNxk8eDDdunWjsrKSzz//nDfffJP58+cDYDKZmDx5Mo899hg9evQgJSWFadOmkZiYyIQJE5ruJz1ZUV1h11K6mHL5XIFFREQa6brrrqO8vJyhQ4disVi4++67+eMf/1jvvAEDBjBnzhxmz57N1KlTGT16NDNnzuS6665znmOz2bj99tvZs2cPYWFhjB8/nmeffbYlf5wW1+jAMnHiRPLy8pg+fTo5OTkMHDiQRYsWOSfNZmZmOoewAEpLS7ntttvYs2cPgYGB9OrVi7feeouJEyc6z7nvvvsoLS3lj3/8IwUFBYwcOZJFixYREBDQBD9iE3FOvM0h80AphmG4TZ4SERE5kmXLljk/r/0Hu6v09HS3r++55x7uuecet2PXXnut8/MXXnihSetrDUyG0ciF5F6oqKiI8PBwCgsLCQsLa55vsvVzeO9KfrYnc6H1CX54KJWYkBacRyMi0s5VVFSwe/duUlJSvOsftHJMR/pv15j3b21+eLxqRlhSzPsBQx1vRUREWpACy/GKTAZMhFBGFMXaU0hERKQFKbAcL98ACOsIOOaxpCuwiIiItBgFlsaIrt1TKJdM3RISERFpMQosjVG7UsicqxEWERGRFqTA0hiuS5sPKrCIiIi0FAWWxoiqvSWUw8FSK0UVVR4uSEREpH1QYGkMt6XNqEW/iIhIC1FgaYzIFADCKSGcEm2CKCIiHmUymfjkk088XUaLUGBpDL8gCE0EHPNY1ItFRESO5cILL2T8+PENPrdy5UpMJhObNm06oWvv27eP884772TKazUUWBorynVpswKLiIgc3U033cTixYvZs2dPvedeffVVBg8eTP/+/Rt1TavVCkB8fDz+/u1jmxgFlsaKctwWSjHl6JaQiIgc0wUXXEBsbCyvvfaa2/GSkhI++OADJkyYwJVXXknHjh0JCgqiX79+vPvuu27njh07ljvuuIPJkycTExNDWloaUP+W0P3330/Pnj0JCgqia9euTJs2jaqqugUiDz/8MAMHDuTNN98kOTmZ8PBwrrjiCoqLi53n2O12nnzySbp3746/vz+dO3fm8ccfdz6flZXF5ZdfTkREBFFRUVx88cX1Nm9sDgosjVU7wmLO1dJmEREPMwyDsqoyjzyOd+9gHx8frrvuOl577TW313zwwQfYbDauueYaBg0axGeffcYvv/zCH//4R6699lrWrVvndp3XX38dPz8/vv32WxYsWNDg9woNDeW1115j8+bNPPfcc7z88ss8++yzbufs3LmTTz75hE8//ZRPP/2U5cuXM2vWLOfzU6dOZdasWUybNo3NmzfzzjvvEBcXB0BVVRVpaWmEhoaycuVKvv32W0JCQhg/frxz1Ke5aLfmxvr1E/jgejbYu/MH6yNsfXQ8Ab6W5v2eIiLS4I6/ZVVlDHtnmEfqWXvVWoJ8g47r3K1bt9K7d2+WLl3K2LFjARg9ejRdunThzTffrHf+BRdcQK9evXj66acBxwhLUVERGzZscDvPZDLx8ccfM2HChAa/79NPP817773HDz/8ADhGWJ566ilycnIIDQ0F4L777mPFihV89913FBcXExsby4svvsjNN99c73pvvfUWjz32GFu2bMFkMgGO21MRERF88sknjBs3rsE6mmK3Zp+jPiv1uXS7Bcg6WEaPuFBPViQiIl6uV69enHnmmbzyyiuMHTuWHTt2sHLlSh555BFsNhtPPPEE77//PtnZ2VitViorKwkKcg9DgwYNOub3WbhwIc8//zw7d+6kpKSE6urqekEgOTnZGVYAEhIS2L/f0a5jy5YtVFZWcs455zR4/Z9++okdO3a4vR4cgWTnzp3H9bs4UQosjVUTWKIoJoxS0g8osIiIeEqgTyBrr1rrse/dGDfddBN33nkn8+bN49VXX6Vbt26MGTOG2bNn89xzzzF37lz69etHcHAwkydPrneLJTg4+KjXX7NmDVdffTV/+9vfSEtLIzw8nPfee49nnnnG7TxfX1+3r00mE3a73fEzBR79ZyopKWHQoEG8/fbb9Z6LjY096mtPlgJLY/mHQEgclOTS2ZRLhibeioh4jMlkOu7bMp52+eWXc/fdd/POO+/wxhtvcOutt2Iymfj222+5+OKLueaaawDHpNfffvuNPn36NOr6q1evpkuXLvz1r391HsvIyGjUNXr06EFgYCBLlixp8JbQ6aefzsKFC+nQoUPzT8E4jCbdngjnnkK56sUiIiLHJSQkhIkTJzJ16lT27dvHDTfcADhCwuLFi1m9ejVbtmzhT3/6E7m5uY2+fo8ePcjMzOS9995j586dPP/883z88ceNukZAQAD3338/9913H2+88QY7d+7ku+++41//+hcAV199NTExMVx88cWsXLmS3bt3s2zZMu66664Gl203JQWWE+GyCWKGVgqJiMhxuummmzh06BBpaWkkJjoakT700EOcfvrppKWlMXbsWOLj4484ifZoLrroIu655x7uuOMOBg4cyOrVq5k2bVqjrzNt2jT+8pe/MH36dHr37s3EiROdc1yCgoJYsWIFnTt35g9/+AO9e/fmpptuoqKiotlHXLRK6ESseAq+eYx/20bzQtgUlv/fWc3/PUVE2rkjrTQR79cUq4Q0wnIiXHZtzj5UTpXN7uGCRERE2jYFlhPhMoel2m6wt6DcwwWJiIi0bQosJ6ImsMSaCgmmXBNvRUREmpkCy4kICIegGMCxCaIm3oqIiDQvBZYT5bpSKF+9WERERJqTAsuJcu3FohEWEZEW0wYWt7Y7TfHfTIHlRDlXCqnbrYhIS6htKV9Wp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6MAyceJE8vLymD59Ojk5OQwcOJBFixY5J81mZmZiNtcN3Jx55pm88847PPTQQzz44IP06NGDTz75xNmDBeC+++6jtLSUP/7xjxQUFDBy5EgWLVqkHiwiIiICaC8hERER8ZBm68MiIiIi4gkKLCIiIuL1FFhERETE6ymwiIiIiNdTYBERERGv1+hlzd6odqGTNkEUERFpPWrft49nwXKbCCzFxcUA2gRRRESkFSouLiY8PPyo57SJPix2u529e/cSGhqKyWRq0msXFRWRlJREVlaWerzU0O+kYfq91KffScP0e6lPv5P62sPvxDAMiouLSUxMdGs625A2McJiNpvp1KlTs34PbbJYn34nDdPvpT79Thqm30t9+p3U19Z/J8caWamlSbciIiLi9RRYRERExOspsByDv78/M2bMwN/f39OleA39Thqm30t9+p00TL+X+vQ7qU+/E3dtYtKtiIiItG0aYRERERGvp8AiIiIiXk+BRURERLyeAouIiIh4PQWWY5g3bx7JyckEBAQwbNgw1q1b5+mSPGbmzJkMGTKE0NBQOnTowIQJE9i2bZuny/Iqs2bNwmQyMXnyZE+X4nHZ2dlcc801REdHExgYSL9+/fjhhx88XZbH2Gw2pk2bRkpKCoGBgXTr1o1HH330uPZQaUtWrFjBhRdeSGJiIiaTiU8++cTtecMwmD59OgkJCQQGBpKamsr27ds9U2wLOdrvpKqqivvvv59+/foRHBxMYmIi1113HXv37vVcwR6iwHIUCxcuZMqUKcyYMYMNGzYwYMAA0tLS2L9/v6dL84jly5dz++23891337F48WKqqqoYN24cpaWlni7NK3z//ff84x//oH///p4uxeMOHTrEiBEj8PX15YsvvmDz5s0888wzREZGero0j5k9ezbz58/nxRdfZMuWLcyePZsnn3ySF154wdOltajS0lIGDBjAvHnzGnz+ySef5Pnnn2fBggWsXbuW4OBg0tLSqKioaOFKW87RfidlZWVs2LCBadOmsWHDBj766CO2bdvGRRdd5IFKPcyQIxo6dKhx++23O7+22WxGYmKiMXPmTA9W5T32799vAMby5cs9XYrHFRcXGz169DAWL15sjBkzxrj77rs9XZJH3X///cbIkSM9XYZXOf/8840bb7zR7dgf/vAH4+qrr/ZQRZ4HGB9//LHza7vdbsTHxxtPPfWU81hBQYHh7+9vvPvuux6osOUd/jtpyLp16wzAyMjIaJmivIRGWI7AarWyfv16UlNTncfMZjOpqamsWbPGg5V5j8LCQgCioqI8XInn3X777Zx//vlu/3tpz/773/8yePBgLrvsMjp06MBpp53Gyy+/7OmyPOrMM89kyZIl/PbbbwD89NNPrFq1ivPOO8/DlXmP3bt3k5OT4/b/o/DwcIYNG6a/uy4KCwsxmUxERER4upQW1SY2P2wO+fn52Gw24uLi3I7HxcWxdetWD1XlPex2O5MnT2bEiBGceuqpni7Ho9577z02bNjA999/7+lSvMauXbuYP38+U6ZM4cEHH+T777/nrrvuws/Pj+uvv97T5XnEAw88QFFREb169cJisWCz2Xj88ce5+uqrPV2a18jJyQFo8O9u7XPtXUVFBffffz9XXnllm94QsSEKLHJCbr/9dn755RdWrVrl6VI8Kisri7vvvpvFixcTEBDg6XK8ht1uZ/DgwTzxxBMAnHbaafzyyy8sWLCg3QaW999/n7fffpt33nmHvn37snHjRiZPnkxiYmK7/Z1I41RVVXH55ZdjGAbz58/3dDktTreEjiAmJgaLxUJubq7b8dzcXOLj4z1UlXe44447+PTTT1m6dCmdOnXydDketX79evbv38/pp5+Oj48PPj4+LF++nOeffx4fHx9sNpunS/SIhIQE+vTp43asd+/eZGZmeqgiz/u///s/HnjgAa644gr69evHtddeyz333MPMmTM9XZrXqP3bqr+79dWGlYyMDBYvXtzuRldAgeWI/Pz8GDRoEEuWLHEes9vtLFmyhOHDh3uwMs8xDIM77riDjz/+mG+++YaUlBRPl+Rx55xzDj///DMbN250PgYPHszVV1/Nxo0bsVgsni7RI0aMGFFvyftvv/1Gly5dPFSR55WVlWE2u//JtVgs2O12D1XkfVJSUoiPj3f7u1tUVMTatWvb7d9dqAsr27dv5+uvvyY6OtrTJXmEbgkdxZQpU7j++usZPHgwQ4cOZe7cuZSWljJp0iRPl+YRt99+O++88w7/+c9/CA0Ndd5TDg8PJzAw0MPVeUZoaGi9OTzBwcFER0e367k999xzD2eeeSZPPPEEl19+OevWreOll17ipZde8nRpHnPhhRfy+OOP07lzZ/r27cuPP/7InDlzuPHGGz1dWosqKSlhx44dzq93797Nxo0biYqKonPnzkyePJnHHnuMHj16kJKSwrRp00hMTGTChAmeK7qZHe13kpCQwKWXXsqGDRv49NNPsdlszr+9UVFR+Pn5earslufpZUre7oUXXjA6d+5s+Pn5GUOHDjW+++47T5fkMUCDj1dffdXTpXkVLWt2+N///meceuqphr+/v9GrVy/jpZde8nRJHlVUVGTcfffdRufOnY2AgACja9euxl//+lejsrLS06W1qKVLlzb4d+T66683DMOxtHnatGlGXFyc4e/vb5xzzjnGtm3bPFt0Mzva72T37t1H/Nu7dOlST5feokyG0c7aLIqIiEirozksIiIi4vUUWERERMTrKbCIiIiI11NgEREREa+nwCIiIiJeT4FFREREvJ4Ci4iIiHg9BRYRERHxegosIiIi4vUUWERERMTrKbCIiIiI11NgEREREa/3/2JvAyYaPDiIAAAAAElFTkSuQmCC", - "text/plain": [ - "
    " - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "execution_count": 4, + "id": "a89ea0e9", + "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()" + "from numpy import asarray\n", + "from numpy import arange\n", + "from numpy.random import rand\n", + "from numpy.random import seed\n", + "from matplotlib import pyplot\n", + " \n", + "# objective function\n", + "def objective(x):\n", + "\treturn x**2.0\n", + " \n", + "# derivative of objective function\n", + "def derivative(x):\n", + "\treturn x * 2.0\n", + " \n", + "# gradient descent algorithm\n", + "def gradient_descent(objective, derivative, bounds, n_iter, step_size):\n", + "\t# track all solutions\n", + "\tsolutions, scores = list(), list()\n", + "\t# generate an initial point\n", + "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", + "\t# run the gradient descent\n", + "\tfor i in range(n_iter):\n", + "\t\t# calculate gradient\n", + "\t\tgradient = derivative(solution)\n", + "\t\t# take a step\n", + "\t\tsolution = solution - step_size * gradient\n", + "\t\t# evaluate candidate point\n", + "\t\tsolution_eval = objective(solution)\n", + "\t\t# store solution\n", + "\t\tsolutions.append(solution)\n", + "\t\tscores.append(solution_eval)\n", + "\t\t# report progress\n", + "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", + "\treturn [solutions, scores]\n", + " \n", + "# seed the pseudo random number generator\n", + "seed(4)\n", + "# define range for input\n", + "bounds = asarray([[-1.0, 1.0]])\n", + "# define the total iterations\n", + "n_iter = 30\n", + "# define the step size\n", + "step_size = 0.1\n", + "# perform the gradient descent search\n", + "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)\n", + "# sample input range uniformly at 0.1 increments\n", + "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", + "# compute targets\n", + "results = objective(inputs)\n", + "# create a line plot of input vs result\n", + "pyplot.plot(inputs, results)\n", + "# plot the solutions found\n", + "pyplot.plot(solutions, scores, '.-', color='red')\n", + "# show the plot\n", + "pyplot.show()" ] }, { "cell_type": "markdown", - "id": "d638746f", - "metadata": {}, + "id": "4a29024a", + "metadata": { + "editable": true + }, "source": [ - "## Summing up\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", - "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", - "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", - "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest." - ] - }, - { - "cell_type": "markdown", - "id": "6fe999c4", - "metadata": {}, - "source": [ - "## Another Example from Scikit-Learn's Repository\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 and 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." + "## Same code but now with momentum gradient descent" ] }, { "cell_type": "code", - "execution_count": 7, - "id": "8289e153", - "metadata": {}, - "outputs": [ - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAABGQAAAHTCAYAAABhg86vAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAADlnUlEQVR4nOzdd3xN9x/H8de92VsSmyD2Vrv2FqtojaJWtShVtFWlv+peVodSbVVttVt+lNp7K2rHiL2FDElk3PP7I7/cigQJkcjN+/l45ME994zvyU3e95vP/Z7vMRmGYSAiIiIiIiIiIunGnNENEBERERERERHJalSQERERERERERFJZyrIiIiIiIiIiIikMxVkRERERERERETSmQoyIiIiIiIiIiLpTAUZEREREREREZF0poKMiIiIiIiIiEg6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xxhvWEUqDBg0iKiqKZ555hpiYGGbPns3OnTuZNm1akg8drl69yj///MPrr7/+0OM/ldLxjk5Ppbtvf/cg997+7tSpU8YHH3xgPPvss0bOnDkNe3t7I0eOHEbLli2NtWvXJtr2Qbe/A4x169Y9iVNL4s6dO8agQYOM8uXLG56enoaDg4NRsGBB45VXXkn2lmzAQ2/p+aDbXu/YscNo3ry5kTt3bsPBwcEoXry48fnnnye5TZ5hGMbChQuN2rVrG25uboabm5tRsmRJ4/XXXzeOHTuWonM7ePCg0bRpU8PV1dXIli2b8dJLLxmXL19Ost6DbiV47+vQunVro1GjRg899sNufTp+/HjDy8sr2fN+XNzn9nX3vnanTp0yOnToYBQqVMhwdnY2XF1djcqVKxs//vijYbFYEm37sNst3mvdunVGQECA4eXlZTg7OxtFihQxevbsaezevTtF53Du3Dmjffv2hqenp+Hu7m60atXKOH78eJL1evTocd823XvLvBdffNGoXbt2io4vWVNWyv6goKBU3Tr1ftm/Z88eo3Hjxoabm5vh4eFhtGnTxggMDEy0znfffWdUq1bN8PHxMezt7Y08efIYXbt2TfZ32jDSJ/tXrlxptGrVysibN6/h4OBgeHh4GLVq1TKmTJmSJP8Mw7ayP0HCrULHjRv30H0n/GzHxsY+cL2n8bWrXr260bVr1xQdX7KmrJT9hvFvPz25r3uz4t5lD9oWMD788MNE2x89etRo37694efnZ/0bY8iQIcbt27eTbdej9h0f9J527+2o33zzTaNw4cKGk5OTkSNHDqNLly7GyZMnk93vwIEDjaJFiz70+A+77fXSpUsNk8n02LdfHj9+vFG7dm0je/bs1p+35557zti4cWOSdRP67g+T3HtHan9eT548aXTv3t36912+fPmMVq1aGQsWLEjReRUsWPC+x7r779EpU6YYFSpUsPY5GjVqlOR3LcHEiRMNV1dXIzQ0NEVteNqYDOMRZkgSyQI2bdpE/fr1OXr06GNNENiiRQvc3d2ZN29eGrZO7ufy5cv4+/szZ84cjZARkVRT9mdO+/bto1KlSvz999+PPH+ciGRdp06domTJkixfvpxGjRo98n769+/P7t272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7Lfe//89blv63/RUqWtSpbRAQoPbnFW/unzdfu8jf8Y/b/4dvWVL78xsNZEQKkdyxPncOfv0VwsOhWrWL3xcXBzVqQNmysHkzlCgBkZHgdLqP062IV47LtJiz+ThvLInm+Hn3q7KrlQji4a416Vyn5B++Ktub2+fN1y7yb/1Z+7O7Hx4OdeuCw6H251fe3D9vvnaRf+uv2n/oEISEwB13uI+ZN0/tz480kBERucrSs1x8ue4w767Yz/lU92abTSuG8ej1tWhaKfx/jvfm9nnztYuId/Pm/nnztYuId/u7/fvz++tFROQP+fvYGXptFVaN78B97avi72Mj6nA8vd7/lWHToth3OimvT1FERERERPIpDWRERP6j0CI+PNytFqvGd6BfZHlsBizZdZquk1bzyOxtnEpIz+tTFBERERGRfEYDGRGRK6RkiD8v33YNi8e2o2vdkpgWfB11lHYTV/Dqwj0kpGXl9SmKiIiIiEg+oYGMiMgVVq1EEB8MbMq397aiWaUwMpwmU1bGcP2k1Xl9aiIiIiIikk9oICMicpU0qRjGrOEt+fiuptQoGURiujOvT0lERERERPIJDWRERK4iwzDoVLskP93flud71M3r0xERERERkXxCAxkREQ+w2wxua1wur09DRERERETyCQ1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD9NARkRERERERETEwzSQERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD3PkxSe1LAuAxMTEvPj0IiJ5Irt52Q30Juq+iHgrtV/tFxHv83fbnycDmaSkJADKly+fF59eRCRPJSUlERoamten4VHqvoh4O7VfRMT7/FX7DSsPxvWmaXLixAmCg4MxDMPTn15EJE9YlkVSUhJlypTBZvOuJ0bVfRHxVmq/2i8i3ufvtj9PBjIiIiIiIiIiIt7Mu8b0IiIiIiIiIiL5gAYyIiIiIiIiIiIepoGMiIiIiIiIiIiHaSAjIiIiIiIiIuJhGsiIiIiIiIiIiHiYBjIiIiIiIiIiIh6mgYyIiIiIiIiIiIdpICOF3tmzZylVqhQvvfRSzvetXbsWX19fli1blodnJiIiV4vaLyLifdR+KWgMy7KsvD4JkattwYIF3HLLLaxdu5aaNWvSsGFDevTowRtvvJHXpyYiIleJ2i8i4n3UfilINJARrzFy5EiWLl1K06ZN2b59Oxs3bsTPzy+vT0tERK4itV9ExPuo/VJQaCAjXiMtLY169epx9OhRNm3aRP369fP6lERE5CpT+0VEvI/aLwWF9pARrxETE8OJEycwTZNDhw7l9emIiIgHqP0iIt5H7ZeCQnfIiFfIzMwkMjKShg0bUrNmTSZNmsT27dspUaJEXp+aiIhcJWq/iIj3UfulINFARrzC+PHjmT17Nlu3biUoKIh27doRGhrKvHnz8vrURETkKlH7RUS8j9ovBYkeWZJCb+XKlUyaNIkvvviCkJAQbDYbX3zxBWvWrGHKlCl5fXoiInIVqP0iIt5H7ZeCRnfIiIiIiIiIiIh4mO6QERERERERERHxMA1kREREREREREQ8TAMZEREREREREREP00BGRERERERERMTDNJAREREREREREfEwDWRERERERERERDxMAxkREREREREREQ/TQEZERERERERExMM0kBERERERERER8TANZEREREREREREPEwDGRERERERERERD/t/fgPmJNNk03EAAAAASUVORK5CYII=", - "text/plain": [ - "
    " - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "execution_count": 5, + "id": "9212126a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "\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 = 300\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()" + "from numpy import asarray\n", + "from numpy import arange\n", + "from numpy.random import rand\n", + "from numpy.random import seed\n", + "from matplotlib import pyplot\n", + " \n", + "# objective function\n", + "def objective(x):\n", + "\treturn x**2.0\n", + " \n", + "# derivative of objective function\n", + "def derivative(x):\n", + "\treturn x * 2.0\n", + " \n", + "# gradient descent algorithm\n", + "def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):\n", + "\t# track all solutions\n", + "\tsolutions, scores = list(), list()\n", + "\t# generate an initial point\n", + "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", + "\t# keep track of the change\n", + "\tchange = 0.0\n", + "\t# run the gradient descent\n", + "\tfor i in range(n_iter):\n", + "\t\t# calculate gradient\n", + "\t\tgradient = derivative(solution)\n", + "\t\t# calculate update\n", + "\t\tnew_change = step_size * gradient + momentum * change\n", + "\t\t# take a step\n", + "\t\tsolution = solution - new_change\n", + "\t\t# save the change\n", + "\t\tchange = new_change\n", + "\t\t# evaluate candidate point\n", + "\t\tsolution_eval = objective(solution)\n", + "\t\t# store solution\n", + "\t\tsolutions.append(solution)\n", + "\t\tscores.append(solution_eval)\n", + "\t\t# report progress\n", + "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", + "\treturn [solutions, scores]\n", + " \n", + "# seed the pseudo random number generator\n", + "seed(4)\n", + "# define range for input\n", + "bounds = asarray([[-1.0, 1.0]])\n", + "# define the total iterations\n", + "n_iter = 30\n", + "# define the step size\n", + "step_size = 0.1\n", + "# define momentum\n", + "momentum = 0.3\n", + "# perform the gradient descent search with momentum\n", + "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)\n", + "# sample input range uniformly at 0.1 increments\n", + "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", + "# compute targets\n", + "results = objective(inputs)\n", + "# create a line plot of input vs result\n", + "pyplot.plot(inputs, results)\n", + "# plot the solutions found\n", + "pyplot.plot(solutions, scores, '.-', color='red')\n", + "# show the plot\n", + "pyplot.show()" ] }, { "cell_type": "markdown", - "id": "3a9dffce", - "metadata": {}, + "id": "c12221ee", + "metadata": { + "editable": true + }, "source": [ - "## Various steps in cross-validation\n", + "## Overview video on Stochastic Gradient Descent\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)." + "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)" ] }, { "cell_type": "markdown", - "id": "2ee67263", - "metadata": {}, + "id": "89e21421", + "metadata": { + "editable": true + }, "source": [ - "## Cross-validation in brief\n", + "## Batches and mini-batches\n", "\n", - "For the various values of $k$\n", + "In gradient descent we compute the cost function and its gradient for all data points we have.\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", - "5. Summarize the model using the sample of model evaluation scores" + "In large-scale applications such as the [ILSVRC challenge](https://www.image-net.org/challenges/LSVRC/), the\n", + "training data can have on order of millions of examples. Hence, it\n", + "seems wasteful to compute the full cost function over the entire\n", + "training set in order to perform only a single parameter update. A\n", + "very common approach to addressing this challenge is to compute the\n", + "gradient over batches of the training data. For example, a typical batch could contain some thousand examples from\n", + "an entire training set of several millions. This batch is then used to\n", + "perform a parameter update." ] }, { "cell_type": "markdown", - "id": "c44868f2", - "metadata": {}, + "id": "b3d6706b", + "metadata": { + "editable": true + }, "source": [ - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", + "## Stochastic Gradient Descent (SGD)\n", "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." + "In stochastic gradient descent, the extreme case is the case where we\n", + "have only one batch, that is we include the whole data set.\n", + "\n", + "This process is called Stochastic Gradient\n", + "Descent (SGD) (or also sometimes on-line gradient descent). This is\n", + "relatively less common to see because in practice due to vectorized\n", + "code optimizations it can be computationally much more efficient to\n", + "evaluate the gradient for 100 examples, than the gradient for one\n", + "example 100 times. Even though SGD technically refers to using a\n", + "single example at a time to evaluate the gradient, you will hear\n", + "people use the term SGD even when referring to mini-batch gradient\n", + "descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD\n", + "for “Batch gradient descent” are rare to see), where it is usually\n", + "assumed that mini-batches are used. The size of the mini-batch is a\n", + "hyperparameter but it is not very common to cross-validate or bootstrap it. It is\n", + "usually based on memory constraints (if any), or set to some value,\n", + "e.g. 32, 64 or 128. We use powers of 2 in practice because many\n", + "vectorized operation implementations work faster when their inputs are\n", + "sized in powers of 2.\n", + "\n", + "In our notes with SGD we mean stochastic gradient descent with mini-batches." + ] + }, + { + "cell_type": "markdown", + "id": "f2900e4e", + "metadata": { + "editable": true + }, + "source": [ + "## Stochastic Gradient Descent\n", + "\n", + "Stochastic gradient descent (SGD) and variants thereof address some of\n", + "the shortcomings of the Gradient descent method discussed above.\n", + "\n", + "The underlying idea of SGD comes from the observation that the cost\n", + "function, which we want to minimize, can almost always be written as a\n", + "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$," + ] + }, + { + "cell_type": "markdown", + "id": "b6745dec", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b6f524f1", + "metadata": { + "editable": true + }, + "source": [ + "## Computation of gradients\n", + "\n", + "This in turn means that the gradient can be\n", + "computed as a sum over $i$-gradients" + ] + }, + { + "cell_type": "markdown", + "id": "db7c028a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "813b7f85", + "metadata": { + "editable": true + }, + "source": [ + "Stochasticity/randomness is introduced by only taking the\n", + "gradient on a subset of the data called minibatches. If there are $n$\n", + "data points and the size of each minibatch is $M$, there will be $n/M$\n", + "minibatches. We denote these minibatches by $B_k$ where\n", + "$k=1,\\cdots,n/M$." + ] + }, + { + "cell_type": "markdown", + "id": "a562fa9a", + "metadata": { + "editable": true + }, + "source": [ + "## SGD example\n", + "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", + "and we choose to have $M=5$ minibathces,\n", + "then each minibatch contains two data points. In particular we have\n", + "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n", + "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n", + "have only a single batch with all data points and on the other extreme,\n", + "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n", + "$B_k = \\mathbf{x}_k$.\n", + "\n", + "The idea is now to approximate the gradient by replacing the sum over\n", + "all data points with a sum over the data points in one the minibatches\n", + "picked at random in each gradient descent step" + ] + }, + { + "cell_type": "markdown", + "id": "75d84b18", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_{\\beta}\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n", + "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0cf6f343", + "metadata": { + "editable": true + }, + "source": [ + "## The gradient step\n", + "\n", + "Thus a gradient descent step now looks like" + ] + }, + { + "cell_type": "markdown", + "id": "44f85de2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta})\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "92851949", + "metadata": { + "editable": true + }, + "source": [ + "where $k$ is picked at random with equal\n", + "probability from $[1,n/M]$. An iteration over the number of\n", + "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", + "typical to choose a number of epochs and for each epoch iterate over\n", + "the number of minibatches, as exemplified in the code below." + ] + }, + { + "cell_type": "markdown", + "id": "21d2691e", + "metadata": { + "editable": true + }, + "source": [ + "## Simple example code" ] }, { "cell_type": "code", "execution_count": 6, - "id": "df0c5466", - "metadata": {}, + "id": "6536b711", + "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", + "import numpy as np \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 = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 10 #number of epochs\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()" + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for \n", + " j += 1" ] }, { "cell_type": "markdown", - "id": "5cbfeb1f", - "metadata": {}, + "id": "4005ce6c", + "metadata": { + "editable": true + }, "source": [ - "## More examples on bootstrap and cross-validation and errors" + "Taking the gradient only on a subset of the data has two important\n", + "benefits. First, it introduces randomness which decreases the chance\n", + "that our opmization scheme gets stuck in a local minima. Second, if\n", + "the size of the minibatches are small relative to the number of\n", + "datapoints ($M < n$), the computation of the gradient is much\n", + "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", + "all $n$ datapoints." + ] + }, + { + "cell_type": "markdown", + "id": "adec9808", + "metadata": { + "editable": true + }, + "source": [ + "## When do we stop?\n", + "\n", + "A natural question is when do we stop the search for a new minimum?\n", + "One possibility is to compute the full gradient after a given number\n", + "of epochs and check if the norm of the gradient is smaller than some\n", + "threshold and stop if true. However, the condition that the gradient\n", + "is zero is valid also for local minima, so this would only tell us\n", + "that we are close to a local/global minimum. However, we could also\n", + "evaluate the cost function at this point, store the result and\n", + "continue the search. If the test kicks in at a later stage we can\n", + "compare the values of the cost function and keep the $\\beta$ that\n", + "gave the lowest value." + ] + }, + { + "cell_type": "markdown", + "id": "deecc226", + "metadata": { + "editable": true + }, + "source": [ + "## Slightly different approach\n", + "\n", + "Another approach is to let the step length $\\gamma_j$ depend on the\n", + "number of epochs in such a way that it becomes very small after a\n", + "reasonable time such that we do not move at all. Such approaches are\n", + "also called scaling. There are many such ways to [scale the learning\n", + "rate](https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1)\n", + "and [discussions here](https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf). See\n", + "also\n", + "\n", + "for a discussion of different scaling functions for the learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "73685769", + "metadata": { + "editable": true + }, + "source": [ + "## Time decay rate\n", + "\n", + "As an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", + "\n", + "In this way we can fix the number of epochs, compute $\\beta$ and\n", + "evaluate the cost function at the end. Repeating the computation will\n", + "give a different result since the scheme is random by design. Then we\n", + "pick the final $\\beta$ that gives the lowest value of the cost\n", + "function." ] }, { "cell_type": "code", "execution_count": 7, - "id": "34028f77", - "metadata": {}, + "id": "6484bffa", + "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", + "import numpy as np \n", "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", + "def step_length(t,t0,t1):\n", + " return t0/(t+t1)\n", "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 500 #number of epochs\n", + "t0 = 1.0\n", + "t1 = 10\n", "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", + "gamma_j = t0/t1\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for beta\n", + " t = epoch*m+i\n", + " gamma_j = step_length(t,t0,t1)\n", + " j += 1\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=False).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()" + "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" ] }, { "cell_type": "markdown", - "id": "9c64885c", - "metadata": {}, + "id": "2438f642", + "metadata": { + "editable": true + }, "source": [ - "Note that we kept the intercept column in the fitting here. This means that we need to set the **intercept** in the call to the **Scikit-Learn** function as **False**. Alternatively, we could have set up the design matrix $X$ without the first column of ones." - ] - }, - { - "cell_type": "markdown", - "id": "ff70b35f", - "metadata": {}, - "source": [ - "## The same example but now with cross-validation\n", + "## Code with a Number of Minibatches which varies\n", "\n", - "In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error." + "In the code here we vary the number of mini-batches." ] }, { "cell_type": "code", "execution_count": 8, - "id": "e21b19fd", - "metadata": {}, + "id": "8d624cf1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ - "# Common imports\n", - "import os\n", + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\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 = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\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", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", + "theta = np.random.randn(2,1)\n", "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)\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(fit_intercept=False)\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.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "cc43a51c", - "metadata": {}, + "id": "6e9eb916", + "metadata": { + "editable": true + }, "source": [ - "## Material for the lab sessions" + "## Replace or not\n", + "\n", + "In the above code, we have use replacement in setting up the\n", + "mini-batches. The discussion\n", + "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", + "useful." ] }, { "cell_type": "markdown", - "id": "af5687ed", - "metadata": {}, + "id": "c60a0137", + "metadata": { + "editable": true + }, "source": [ - "## Linking the regression analysis with a statistical interpretation\n", + "## Momentum based GD\n", "\n", - "We will now couple the discussions of ordinary least squares, Ridge\n", - "and Lasso regression with a statistical interpretation, that is we\n", - "move from a linear algebra analysis to a statistical analysis. In\n", - "particular, we will focus on what the regularization terms can result\n", - "in. We will amongst other things show that the regularization\n", - "parameter can reduce considerably the variance of the parameters\n", - "$\\beta$.\n", - "\n", - "The\n", - "advantage of doing linear regression is that we actually end up with\n", - "analytical expressions for several statistical quantities. \n", - "Standard least squares and Ridge regression allow us to\n", - "derive quantities like the variance and other expectation values in a\n", - "rather straightforward way.\n", - "\n", - "It is assumed that $\\varepsilon_i\n", - "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", - "independent, i.e.:" + "The stochastic gradient descent (SGD) is almost always used with a\n", + "*momentum* or inertia term that serves as a memory of the direction we\n", + "are moving in parameter space. This is typically implemented as\n", + "follows" ] }, { "cell_type": "markdown", - "id": "47c3811a", - "metadata": {}, + "id": "2d8174d4", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\begin{align*} \n", - "\\mbox{Cov}(\\varepsilon_{i_1},\n", - "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", - "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", - "\\end{align*}\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", - "id": "980dac66", - "metadata": {}, + "id": "afc41240", + "metadata": { + "editable": true + }, "source": [ - "The randomness of $\\varepsilon_i$ implies that\n", - "$\\mathbf{y}_i$ is also a random variable. In particular,\n", - "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", - "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n", - "non-random scalar. To specify the parameters of the distribution of\n", - "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", + "\n", + "
    \n", "\n", - "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", - "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", - "row number $i$ and perform a sum over all values $p$." - ] - }, - { - "cell_type": "markdown", - "id": "be67d8c5", - "metadata": {}, - "source": [ - "## Assumptions made\n", - "\n", - "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n", - "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", - "which describe our data" - ] - }, - { - "cell_type": "markdown", - "id": "5133bf97", - "metadata": {}, - "source": [ "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", - "id": "b76cb41b", - "metadata": {}, + "id": "e3c96a9f", + "metadata": { + "editable": true + }, "source": [ - "We approximate this function with our model from the solution of the linear regression equations, that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" + "where we have introduced a momentum parameter $\\gamma$, with\n", + "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", + "indicate the gradient is to be taken over a different mini-batch at\n", + "each step. We call this algorithm gradient descent with momentum\n", + "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", + "running average of recently encountered gradients and\n", + "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", + "used in the averaging procedure. Consistent with this, when\n", + "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", + "earlier. An equivalent way of writing the updates is" ] }, { "cell_type": "markdown", - "id": "b6e9e9ce", - "metadata": {}, + "id": "74e0e345", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", + "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", "$$" ] }, { "cell_type": "markdown", - "id": "53479926", - "metadata": {}, + "id": "288fcc66", + "metadata": { + "editable": true + }, "source": [ - "## Expectation value and variance\n", - "\n", - "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." ] }, { "cell_type": "markdown", - "id": "1929fd98", - "metadata": {}, + "id": "63b49aca", + "metadata": { + "editable": true + }, + "source": [ + "## More on momentum based approaches\n", + "\n", + "Let us try to get more intuition from these equations. It is helpful\n", + "to consider a simple physical analogy with a particle of mass $m$\n", + "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", + "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n", + "then its motion is described by" + ] + }, + { + "cell_type": "markdown", + "id": "94b37496", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(y_i) & =\n", - "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", - "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", + "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", "$$" ] }, { "cell_type": "markdown", - "id": "18b53cb3", - "metadata": {}, + "id": "3a439485", + "metadata": { + "editable": true + }, "source": [ - "while\n", - "its variance is" + "We can discretize this equation in the usual way to get" ] }, { "cell_type": "markdown", - "id": "a57528a8", - "metadata": {}, + "id": "ff92e318", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n", - "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n", - "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", - "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", - "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", - "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", - "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", - "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", - "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", - "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", - "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", - "\\end{align*}\n", + "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", "$$" ] }, { "cell_type": "markdown", - "id": "b5e5c863", - "metadata": {}, + "id": "142e0f95", + "metadata": { + "editable": true + }, "source": [ - "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD)." + "Rearranging this equation, we can rewrite this as" ] }, { "cell_type": "markdown", - "id": "13fe1b50", - "metadata": {}, - "source": [ - "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", - "\n", - "With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ we can evaluate the expectation value" - ] - }, - { - "cell_type": "markdown", - "id": "22327251", - "metadata": {}, + "id": "88d4ce9a", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n", + "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", "$$" ] }, { "cell_type": "markdown", - "id": "f7875671", - "metadata": {}, + "id": "5c662618", + "metadata": { + "editable": true + }, "source": [ - "This means that the estimator of the regression parameters is unbiased.\n", + "## Momentum parameter\n", "\n", - "We can also calculate the variance\n", - "\n", - "The variance of the optimal value $\\boldsymbol{\\hat{\\beta}}$ is" + "Notice that this equation is identical to previous one if we identify\n", + "the position of the particle, $\\mathbf{w}$, with the parameters\n", + "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n", + "parameter and learning rate with the mass of the particle and the\n", + "viscous drag as:" ] }, { "cell_type": "markdown", - "id": "584d9150", - "metadata": {}, + "id": "2c4a2172", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\begin{eqnarray*}\n", - "\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", - "\\\\\n", - "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} - \\boldsymbol{\\beta}]^{T} \\}\n", - "\\\\\n", - "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} \\, \\mathbf{y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{y} \\, \\mathbf{y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n", - "% \\\\\n", - "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", - "\\\\\n", - "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", - "\\end{eqnarray*}\n", + "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "0ebb2d20", - "metadata": {}, + "id": "630c69f8", + "metadata": { + "editable": true + }, "source": [ - "where we have used that $\\mathbb{E} (\\mathbf{y} \\mathbf{y}^{T}) =\n", - "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", - "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", - "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", - "variance of the estimate of the $j$-th regression coefficient:\n", - "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n", - "construct a confidence interval for the estimates.\n", + "Thus, as the name suggests, the momentum parameter is proportional to\n", + "the mass of the particle and effectively provides inertia.\n", + "Furthermore, in the large viscosity/small learning rate limit, our\n", + "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", "\n", - "In a similar way, we can obtain analytical expressions for say the\n", - "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", - "when we employ Ridge regression, allowing us again to define a confidence interval. \n", + "Why is momentum useful? SGD momentum helps the gradient descent\n", + "algorithm gain speed in directions with persistent but small gradients\n", + "even in the presence of stochasticity, while suppressing oscillations\n", + "in high-curvature directions. This becomes especially important in\n", + "situations where the landscape is shallow and flat in some directions\n", + "and narrow and steep in others. It has been argued that first-order\n", + "methods (with appropriate initial conditions) can perform comparable\n", + "to more expensive second order methods, especially in the context of\n", + "complex deep learning models.\n", "\n", - "It is rather straightforward to show that" + "These beneficial properties of momentum can sometimes become even more\n", + "pronounced by using a slight modification of the classical momentum\n", + "algorithm called Nesterov Accelerated Gradient (NAG).\n", + "\n", + "In the NAG algorithm, rather than calculating the gradient at the\n", + "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n", + "calculates the gradient at the expected value of the parameters given\n", + "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n", + "\\mathbf{v}_{t-1})$. This yields the NAG update rule" ] }, { "cell_type": "markdown", - "id": "b701ef3f", - "metadata": {}, + "id": "7fc49052", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}.\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", - "id": "1453c4df", - "metadata": {}, + "id": "800856ba", + "metadata": { + "editable": true + }, "source": [ - "We see clearly that \n", - "$\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big] \\not= \\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}$ for any $\\lambda > 0$.\n", + "\n", + "
    \n", "\n", - "We can also compute the variance as" - ] - }, - { - "cell_type": "markdown", - "id": "fade84b6", - "metadata": {}, - "source": [ "$$\n", - "\\mbox{Var}[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", + "\\label{_auto2} \\tag{2}\n", + "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", - "id": "e91b254f", - "metadata": {}, + "id": "154d4907", + "metadata": { + "editable": true + }, "source": [ - "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n", - "\n", - "With this, we can compute the difference" + "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$." ] }, { "cell_type": "markdown", - "id": "6f50fb28", - "metadata": {}, + "id": "17557243", + "metadata": { + "editable": true + }, "source": [ + "## Second moment of the gradient\n", + "\n", + "In stochastic gradient descent, with and without momentum, we still\n", + "have to specify a schedule for tuning the learning rates $\\eta_t$\n", + "as a function of time. As discussed in the context of Newton's\n", + "method, this presents a number of dilemmas. The learning rate is\n", + "limited by the steepest direction which can change depending on the\n", + "current position in the landscape. To circumvent this problem, ideally\n", + "our algorithm would keep track of curvature and take large steps in\n", + "shallow, flat directions and small steps in steep, narrow directions.\n", + "Second-order methods accomplish this by calculating or approximating\n", + "the Hessian and normalizing the learning rate by the\n", + "curvature. However, this is very computationally expensive for\n", + "extremely large models. Ideally, we would like to be able to\n", + "adaptively change the step size to match the landscape without paying\n", + "the steep computational price of calculating or approximating\n", + "Hessians.\n", + "\n", + "Recently, a number of methods have been introduced that accomplish\n", + "this by tracking not only the gradient, but also the second moment of\n", + "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", + "[ADAM](https://arxiv.org/abs/1412.6980)." + ] + }, + { + "cell_type": "markdown", + "id": "f3d09840", + "metadata": { + "editable": true + }, + "source": [ + "## RMS prop\n", + "\n", + "In RMS prop, in addition to keeping a running average of the first\n", + "moment of the gradient, we also keep track of the second moment\n", + "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n", + "for RMS prop is given by" + ] + }, + { + "cell_type": "markdown", + "id": "175455a1", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", "$$\n", - "\\mbox{Var}[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}]-\\mbox{Var}(\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto3} \\tag{3}\n", + "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", - "id": "e37b2bfb", - "metadata": {}, + "id": "cf1e9538", + "metadata": { + "editable": true + }, "source": [ - "The difference is non-negative definite since each component of the\n", - "matrix product is non-negative definite. \n", - "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n", + "$$\n", + "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "da9b6589", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cbc7a25f", + "metadata": { + "editable": true + }, + "source": [ + "where $\\beta$ controls the averaging time of the second moment and is\n", + "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", + "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n", + "small regularization constant to prevent divergences. Multiplication\n", + "and division by vectors is understood as an element-wise operation. It\n", + "is clear from this formula that the learning rate is reduced in\n", + "directions where the norm of the gradient is consistently large. This\n", + "greatly speeds up the convergence by allowing us to use a larger\n", + "learning rate for flat directions." + ] + }, + { + "cell_type": "markdown", + "id": "e8064f4a", + "metadata": { + "editable": true + }, + "source": [ + "## [ADAM optimizer](https://arxiv.org/abs/1412.6980)\n", "\n", - "For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended." + "A related algorithm is the ADAM optimizer. In\n", + "[ADAM](https://arxiv.org/abs/1412.6980), we keep a running average of\n", + "both the first and second moment of the gradient and use this\n", + "information to adaptively change the learning rate for different\n", + "parameters. The method isefficient when working with large\n", + "problems involving lots data and/or parameters. It is a combination of the\n", + "gradient descent with momentum algorithm and the RMSprop algorithm\n", + "discussed above.\n", + "\n", + "In addition to keeping a running average of the first and\n", + "second moments of the gradient\n", + "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n", + "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n", + "performs an additional bias correction to account for the fact that we\n", + "are estimating the first two moments of the gradient using a running\n", + "average (denoted by the hats in the update rule below). The update\n", + "rule for ADAM is given by (where multiplication and division are once\n", + "again understood to be element-wise operations below)" + ] + }, + { + "cell_type": "markdown", + "id": "12912817", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto4} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7864ca89", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "02a5d4ef", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "327a1f34", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c5ac526b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e6a33564", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4ffe0088", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\label{_auto5} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "34eb03fb", + "metadata": { + "editable": true + }, + "source": [ + "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", + "second moment and are typically taken to be $0.9$ and $0.99$\n", + "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", + "\n", + "Like in RMSprop, the effective step size of a parameter depends on the\n", + "magnitude of its gradient squared. To understand this better, let us\n", + "rewrite this expression in terms of the variance\n", + "$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n", + "(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n", + "update rule for this parameter is given by" + ] + }, + { + "cell_type": "markdown", + "id": "18f62c05", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5539d5a5", + "metadata": { + "editable": true + }, + "source": [ + "## Algorithms and codes for Adagrad, RMSprop and Adam\n", + "\n", + "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", + "\n", + "The codes which implement these algorithms are discussed below here." + ] + }, + { + "cell_type": "markdown", + "id": "ae04cfe0", + "metadata": { + "editable": true + }, + "source": [ + "## Practical tips\n", + "\n", + "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", + "\n", + "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", + "\n", + "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", + "\n", + "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications." + ] + }, + { + "cell_type": "markdown", + "id": "3ffaaf9a", + "metadata": { + "editable": true + }, + "source": [ + "## Sneaking in automatic differentiation using Autograd\n", + "\n", + "We anticipate our discussions to come in connection with neural networks and automatic differentiation\n", + "by showing how we can use **autograd** for the cases above. Later we will replace **autograd** with **JAX**." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "51503c7d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "67d85da7", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "586da287", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x#+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 30\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "# Now improve with momentum gradient descent\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "for iter in range(Niterations):\n", + " # calculate gradient\n", + " gradients = training_gradient(theta)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd wth momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "b0d53639", + "metadata": { + "editable": true + }, + "source": [ + "## But none of these can compete with Newton's method" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "81089279", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Newton's method\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(beta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "# Note that here the Hessian does not depend on the parameters beta\n", + "invH = np.linalg.pinv(H)\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "beta = np.random.randn(2,1)\n", + "Niterations = 5\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(beta)\n", + " beta -= invH @ gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"beta from own Newton code\")\n", + "print(beta)" + ] + }, + { + "cell_type": "markdown", + "id": "e302b6c8", + "metadata": { + "editable": true + }, + "source": [ + "## Including Stochastic Gradient Descent with Autograd\n", + "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "88efb71c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "a3e14887", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "607e3bc9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 100\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "\n", + "for epoch in range(n_epochs):\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + "print(\"theta from own sdg with momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "d96e1c2c", + "metadata": { + "editable": true + }, + "source": [ + "## Similar (second order function now) problem but now with AdaGrad" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "6cbe854b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " Giter += gradients*gradients\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + " theta -= update\n", + "print(\"theta from own AdaGrad\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "0ed15b7b", + "metadata": { + "editable": true + }, + "source": [ + "Running this code we note an almost perfect agreement with the results from matrix inversion." + ] + }, + { + "cell_type": "markdown", + "id": "d97ab879", + "metadata": { + "editable": true + }, + "source": [ + "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "c58a19a2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameter rho\n", + "rho = 0.99\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + "\t# Accumulated gradient\n", + "\t# Scaling with rho the new and the previous results\n", + " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", + "\t# Taking the diagonal only and inverting\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + "\t# Hadamard product\n", + " theta -= update\n", + "print(\"theta from own RMSprop\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "d7106089", + "metadata": { + "editable": true + }, + "source": [ + "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "d3b9cdb9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", + "beta1 = 0.9\n", + "beta2 = 0.999\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-7\n", + "iter = 0\n", + "for epoch in range(n_epochs):\n", + " first_moment = 0.0\n", + " second_moment = 0.0\n", + " iter += 1\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " # Computing moments first\n", + " first_moment = beta1*first_moment + (1-beta1)*gradients\n", + " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", + " first_term = first_moment/(1.0-beta1**iter)\n", + " second_term = second_moment/(1.0-beta2**iter)\n", + "\t# Scaling with rho the new and the previous results\n", + " update = eta*first_term/(np.sqrt(second_term)+delta)\n", + " theta -= update\n", + "print(\"theta from own ADAM\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "e6a7abff", + "metadata": { + "editable": true + }, + "source": [ + "## Material for the lab sessions\n", + "\n", + "**Material for the lab sessions on Tuesday and Wednesday.**\n", + "\n", + "1. Exercise set for week 37\n", + "\n", + "2. Work on project 1\n", + "\n", + "\n", + " * For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended." ] } ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.15" - } - }, + "metadata": {}, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/src/week37/.ipynb_checkpoints/week37-checkpoint.ipynb b/doc/src/week37/.ipynb_checkpoints/week37-checkpoint.ipynb new file mode 100644 index 000000000..c40ec2419 --- /dev/null +++ b/doc/src/week37/.ipynb_checkpoints/week37-checkpoint.ipynb @@ -0,0 +1,2444 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ebae0536", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "c87edf63", + "metadata": { + "editable": true + }, + "source": [ + "# Week 37: Statistical interpretations and Resampling Methods\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", + "\n", + "Date: **September 8-12, 2025**\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "9b6436c9", + "metadata": { + "editable": true + }, + "source": [ + "## Plans for week 37, lecture Monday\n", + "\n", + "**Plans and material for the lecture on Monday September 8.**\n", + "\n", + "The family of gradient descent methods\n", + "1. Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge\n", + "\n", + "2. Improving gradient descent with momentum\n", + "\n", + "3. Introducing stochastic gradient descent\n", + "\n", + "4. More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "01055296", + "metadata": { + "editable": true + }, + "source": [ + "## Readings and Videos:\n", + "1. Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html\"\n", + "\n", + "2. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.\n", + "\n", + "3. Video on gradient descent at \n", + "\n", + "4. Video on Stochastic gradient descent at " + ] + }, + { + "cell_type": "markdown", + "id": "5b4c3f44", + "metadata": { + "editable": true + }, + "source": [ + "## Material for lecture Monday September 8" + ] + }, + { + "cell_type": "markdown", + "id": "23544472", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient descent and revisiting Ordinary Least Squares from last week\n", + "\n", + "Last week we started with linear regression as a case study for the gradient descent\n", + "methods. Linear regression is a great test case for the gradient\n", + "descent methods discussed in the lectures since it has several\n", + "desirable properties such as:\n", + "\n", + "1. An analytical solution (recall homework sets for week 35).\n", + "\n", + "2. The gradient can be computed analytically.\n", + "\n", + "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\n", + "\n", + "We revisit an example similar to what we had in the first homework set. We have a function of the type" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "d74adaf2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "x = 2*np.random.rand(m,1)\n", + "y = 4+3*x+np.random.randn(m,1)" + ] + }, + { + "cell_type": "markdown", + "id": "fa36c64d", + "metadata": { + "editable": true + }, + "source": [ + "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", + "The linear regression model is given by" + ] + }, + { + "cell_type": "markdown", + "id": "571c791d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "h_\\theta(x) = \\boldsymbol{y} = \\theta_0 + \\theta_1 x,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "12d3e9eb", + "metadata": { + "editable": true + }, + "source": [ + "such that" + ] + }, + { + "cell_type": "markdown", + "id": "17610490", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{y}_i = \\theta_0 + \\theta_1 x_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "47fefa69", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient descent example\n", + "\n", + "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\theta = (\\theta_0, \\theta_1)^T$\n", + "\n", + "It is convenient to write $\\mathbf{\\boldsymbol{y}} = X\\theta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by (we keep the intercept here)" + ] + }, + { + "cell_type": "markdown", + "id": "52eb2d30", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "X \\equiv \\begin{bmatrix}\n", + "1 & x_1 \\\\\n", + "\\vdots & \\vdots \\\\\n", + "1 & x_{100} & \\\\\n", + "\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7d89f32b", + "metadata": { + "editable": true + }, + "source": [ + "The cost/loss/risk function is given by (" + ] + }, + { + "cell_type": "markdown", + "id": "5b0fb490", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\theta) = \\frac{1}{n}||X\\theta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\theta_0 + \\theta_1 x_i)^2 - 2 y_i (\\theta_0 + \\theta_1 x_i) + y_i^2\\right]\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "891f388a", + "metadata": { + "editable": true + }, + "source": [ + "and we want to find $\\theta$ such that $C(\\theta)$ is minimized." + ] + }, + { + "cell_type": "markdown", + "id": "d05ffb4b", + "metadata": { + "editable": true + }, + "source": [ + "## The derivative of the cost/loss function\n", + "\n", + "Computing $\\partial C(\\theta) / \\partial \\theta_0$ and $\\partial C(\\theta) / \\partial \\theta_1$ we can show that the gradient can be written as" + ] + }, + { + "cell_type": "markdown", + "id": "f59689ea", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_{\\theta} C(\\theta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\theta_0+\\theta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\theta_0+\\theta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T(X\\theta - \\mathbf{y}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9a119fe4", + "metadata": { + "editable": true + }, + "source": [ + "where $X$ is the design matrix defined above." + ] + }, + { + "cell_type": "markdown", + "id": "ef5c109f", + "metadata": { + "editable": true + }, + "source": [ + "## The Hessian matrix\n", + "The Hessian matrix of $C(\\theta)$ is given by" + ] + }, + { + "cell_type": "markdown", + "id": "5412ed07", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0^2} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} \\\\\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_1^2} & \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T X.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "33c5d9c9", + "metadata": { + "editable": true + }, + "source": [ + "This result implies that $C(\\theta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite." + ] + }, + { + "cell_type": "markdown", + "id": "a8cf7d20", + "metadata": { + "editable": true + }, + "source": [ + "## Simple program\n", + "\n", + "We can now write a program that minimizes $C(\\theta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" + ] + }, + { + "cell_type": "markdown", + "id": "40f0daf3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\theta_{k+1} = \\theta_k - \\gamma \\nabla_\\theta C(\\theta_k), \\ k=0,1,\\cdots\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b09c9d54", + "metadata": { + "editable": true + }, + "source": [ + "We can use the expression we computed for the gradient and let use a\n", + "$\\theta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", + "when $||\\nabla_\\theta C(\\theta_k) || \\leq \\epsilon = 10^{-8}$. **Note that the code below does not include the latter stop criterion**.\n", + "\n", + "And finally we can compare our solution for $\\theta$ with the analytic result given by \n", + "$\\theta= (X^TX)^{-1} X^T \\mathbf{y}$." + ] + }, + { + "cell_type": "markdown", + "id": "081f1192", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient Descent Example\n", + "\n", + "Here our simple example" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "5842a0a2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "\n", + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", + "\n", + "# the number of datapoints\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "# Hessian matrix\n", + "H = (2.0/n)* X.T @ X\n", + "# Get the eigenvalues\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y\n", + "print(theta_linreg)\n", + "theta = np.random.randn(2,1)\n", + "\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "for iter in range(Niterations):\n", + " gradient = (2.0/n)*X.T @ (X @ theta-y)\n", + " theta -= eta*gradient\n", + "\n", + "print(theta)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(theta)\n", + "ypredict2 = xbnew.dot(theta_linreg)\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "923874ba", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient descent and Ridge\n", + "\n", + "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\theta$," + ] + }, + { + "cell_type": "markdown", + "id": "442c5abb", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C_{\\text{ridge}}(\\theta) = \\frac{1}{n}||X\\theta -\\mathbf{y}||^2 + \\lambda ||\\theta||^2, \\ \\lambda \\geq 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "743e05ca", + "metadata": { + "editable": true + }, + "source": [ + "In order to minimize $C_{\\text{ridge}}(\\theta)$ using GD we adjust the gradient as follows" + ] + }, + { + "cell_type": "markdown", + "id": "27dfced9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_\\theta C_{\\text{ridge}}(\\theta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\theta_0+\\theta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\theta_0+\\theta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\theta_0 \\\\ \\theta_1\\end{bmatrix} = 2 (\\frac{1}{n}X^T(X\\theta - \\mathbf{y})+\\lambda \\theta).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3ff66697", + "metadata": { + "editable": true + }, + "source": [ + "We can easily extend our program to minimize $C_{\\text{ridge}}(\\theta)$ using gradient descent and compare with the analytical solution given by" + ] + }, + { + "cell_type": "markdown", + "id": "f63f80f9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\theta_{\\text{ridge}} = \\left(X^T X + n\\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "dc6a4fff", + "metadata": { + "editable": true + }, + "source": [ + "## The Hessian matrix for Ridge Regression\n", + "The Hessian matrix of Ridge Regression for our simple example is given by" + ] + }, + { + "cell_type": "markdown", + "id": "56a4b43d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0^2} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} \\\\\n", + "\\frac{\\partial^2 C(\\theta)}{\\partial \\theta_0 \\partial \\theta_1} & \\frac{\\partial^2 C(\\theta)}{\\partial \\theta_1^2} & \\\\\n", + "\\end{bmatrix} = \\frac{2}{n}X^T X+2\\lambda\\boldsymbol{I}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "38c6aab3", + "metadata": { + "editable": true + }, + "source": [ + "This implies that the Hessian matrix is positive definite, hence the stationary point is a\n", + "minimum.\n", + "Note that the Ridge cost function is convex being a sum of two convex\n", + "functions. Therefore, the stationary point is a global\n", + "minimum of this function." + ] + }, + { + "cell_type": "markdown", + "id": "a4f724c3", + "metadata": { + "editable": true + }, + "source": [ + "## Program example for gradient descent with Ridge Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "ae5d09dc", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", + "\n", + "# the number of datapoints\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "\n", + "#Ridge parameter lambda\n", + "lmbda = 0.001\n", + "Id = n*lmbda* np.eye(XT_X.shape[0])\n", + "\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])\n", + "# Get the eigenvalues\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "\n", + "theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y\n", + "print(theta_linreg)\n", + "# Start plain gradient descent\n", + "theta = np.random.randn(2,1)\n", + "\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 100\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta\n", + " theta -= eta*gradients\n", + "\n", + "print(theta)\n", + "ypredict = X @ theta\n", + "ypredict2 = X @ theta_linreg\n", + "plt.plot(x, ypredict, \"r-\")\n", + "plt.plot(x, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example for Ridge')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "184d283f", + "metadata": { + "editable": true + }, + "source": [ + "## Using gradient descent methods, limitations\n", + "\n", + "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", + "\n", + "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", + "\n", + "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", + "\n", + "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", + "\n", + "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", + "\n", + "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." + ] + }, + { + "cell_type": "markdown", + "id": "cfb021a5", + "metadata": { + "editable": true + }, + "source": [ + "## Improving gradient descent with momentum\n", + "\n", + "We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "a89ea0e9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from numpy import asarray\n", + "from numpy import arange\n", + "from numpy.random import rand\n", + "from numpy.random import seed\n", + "from matplotlib import pyplot\n", + " \n", + "# objective function\n", + "def objective(x):\n", + "\treturn x**2.0\n", + " \n", + "# derivative of objective function\n", + "def derivative(x):\n", + "\treturn x * 2.0\n", + " \n", + "# gradient descent algorithm\n", + "def gradient_descent(objective, derivative, bounds, n_iter, step_size):\n", + "\t# track all solutions\n", + "\tsolutions, scores = list(), list()\n", + "\t# generate an initial point\n", + "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", + "\t# run the gradient descent\n", + "\tfor i in range(n_iter):\n", + "\t\t# calculate gradient\n", + "\t\tgradient = derivative(solution)\n", + "\t\t# take a step\n", + "\t\tsolution = solution - step_size * gradient\n", + "\t\t# evaluate candidate point\n", + "\t\tsolution_eval = objective(solution)\n", + "\t\t# store solution\n", + "\t\tsolutions.append(solution)\n", + "\t\tscores.append(solution_eval)\n", + "\t\t# report progress\n", + "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", + "\treturn [solutions, scores]\n", + " \n", + "# seed the pseudo random number generator\n", + "seed(4)\n", + "# define range for input\n", + "bounds = asarray([[-1.0, 1.0]])\n", + "# define the total iterations\n", + "n_iter = 30\n", + "# define the step size\n", + "step_size = 0.1\n", + "# perform the gradient descent search\n", + "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)\n", + "# sample input range uniformly at 0.1 increments\n", + "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", + "# compute targets\n", + "results = objective(inputs)\n", + "# create a line plot of input vs result\n", + "pyplot.plot(inputs, results)\n", + "# plot the solutions found\n", + "pyplot.plot(solutions, scores, '.-', color='red')\n", + "# show the plot\n", + "pyplot.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4a29024a", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "9212126a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from numpy import asarray\n", + "from numpy import arange\n", + "from numpy.random import rand\n", + "from numpy.random import seed\n", + "from matplotlib import pyplot\n", + " \n", + "# objective function\n", + "def objective(x):\n", + "\treturn x**2.0\n", + " \n", + "# derivative of objective function\n", + "def derivative(x):\n", + "\treturn x * 2.0\n", + " \n", + "# gradient descent algorithm\n", + "def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):\n", + "\t# track all solutions\n", + "\tsolutions, scores = list(), list()\n", + "\t# generate an initial point\n", + "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", + "\t# keep track of the change\n", + "\tchange = 0.0\n", + "\t# run the gradient descent\n", + "\tfor i in range(n_iter):\n", + "\t\t# calculate gradient\n", + "\t\tgradient = derivative(solution)\n", + "\t\t# calculate update\n", + "\t\tnew_change = step_size * gradient + momentum * change\n", + "\t\t# take a step\n", + "\t\tsolution = solution - new_change\n", + "\t\t# save the change\n", + "\t\tchange = new_change\n", + "\t\t# evaluate candidate point\n", + "\t\tsolution_eval = objective(solution)\n", + "\t\t# store solution\n", + "\t\tsolutions.append(solution)\n", + "\t\tscores.append(solution_eval)\n", + "\t\t# report progress\n", + "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", + "\treturn [solutions, scores]\n", + " \n", + "# seed the pseudo random number generator\n", + "seed(4)\n", + "# define range for input\n", + "bounds = asarray([[-1.0, 1.0]])\n", + "# define the total iterations\n", + "n_iter = 30\n", + "# define the step size\n", + "step_size = 0.1\n", + "# define momentum\n", + "momentum = 0.3\n", + "# perform the gradient descent search with momentum\n", + "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)\n", + "# sample input range uniformly at 0.1 increments\n", + "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", + "# compute targets\n", + "results = objective(inputs)\n", + "# create a line plot of input vs result\n", + "pyplot.plot(inputs, results)\n", + "# plot the solutions found\n", + "pyplot.plot(solutions, scores, '.-', color='red')\n", + "# show the plot\n", + "pyplot.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c12221ee", + "metadata": { + "editable": true + }, + "source": [ + "## Overview video on Stochastic Gradient Descent\n", + "\n", + "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)" + ] + }, + { + "cell_type": "markdown", + "id": "89e21421", + "metadata": { + "editable": true + }, + "source": [ + "## Batches and mini-batches\n", + "\n", + "In gradient descent we compute the cost function and its gradient for all data points we have.\n", + "\n", + "In large-scale applications such as the [ILSVRC challenge](https://www.image-net.org/challenges/LSVRC/), the\n", + "training data can have on order of millions of examples. Hence, it\n", + "seems wasteful to compute the full cost function over the entire\n", + "training set in order to perform only a single parameter update. A\n", + "very common approach to addressing this challenge is to compute the\n", + "gradient over batches of the training data. For example, a typical batch could contain some thousand examples from\n", + "an entire training set of several millions. This batch is then used to\n", + "perform a parameter update." + ] + }, + { + "cell_type": "markdown", + "id": "b3d6706b", + "metadata": { + "editable": true + }, + "source": [ + "## Stochastic Gradient Descent (SGD)\n", + "\n", + "In stochastic gradient descent, the extreme case is the case where we\n", + "have only one batch, that is we include the whole data set.\n", + "\n", + "This process is called Stochastic Gradient\n", + "Descent (SGD) (or also sometimes on-line gradient descent). This is\n", + "relatively less common to see because in practice due to vectorized\n", + "code optimizations it can be computationally much more efficient to\n", + "evaluate the gradient for 100 examples, than the gradient for one\n", + "example 100 times. Even though SGD technically refers to using a\n", + "single example at a time to evaluate the gradient, you will hear\n", + "people use the term SGD even when referring to mini-batch gradient\n", + "descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD\n", + "for “Batch gradient descent” are rare to see), where it is usually\n", + "assumed that mini-batches are used. The size of the mini-batch is a\n", + "hyperparameter but it is not very common to cross-validate or bootstrap it. It is\n", + "usually based on memory constraints (if any), or set to some value,\n", + "e.g. 32, 64 or 128. We use powers of 2 in practice because many\n", + "vectorized operation implementations work faster when their inputs are\n", + "sized in powers of 2.\n", + "\n", + "In our notes with SGD we mean stochastic gradient descent with mini-batches." + ] + }, + { + "cell_type": "markdown", + "id": "f2900e4e", + "metadata": { + "editable": true + }, + "source": [ + "## Stochastic Gradient Descent\n", + "\n", + "Stochastic gradient descent (SGD) and variants thereof address some of\n", + "the shortcomings of the Gradient descent method discussed above.\n", + "\n", + "The underlying idea of SGD comes from the observation that the cost\n", + "function, which we want to minimize, can almost always be written as a\n", + "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$," + ] + }, + { + "cell_type": "markdown", + "id": "b6745dec", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b6f524f1", + "metadata": { + "editable": true + }, + "source": [ + "## Computation of gradients\n", + "\n", + "This in turn means that the gradient can be\n", + "computed as a sum over $i$-gradients" + ] + }, + { + "cell_type": "markdown", + "id": "db7c028a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "813b7f85", + "metadata": { + "editable": true + }, + "source": [ + "Stochasticity/randomness is introduced by only taking the\n", + "gradient on a subset of the data called minibatches. If there are $n$\n", + "data points and the size of each minibatch is $M$, there will be $n/M$\n", + "minibatches. We denote these minibatches by $B_k$ where\n", + "$k=1,\\cdots,n/M$." + ] + }, + { + "cell_type": "markdown", + "id": "a562fa9a", + "metadata": { + "editable": true + }, + "source": [ + "## SGD example\n", + "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", + "and we choose to have $M=5$ minibathces,\n", + "then each minibatch contains two data points. In particular we have\n", + "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n", + "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n", + "have only a single batch with all data points and on the other extreme,\n", + "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n", + "$B_k = \\mathbf{x}_k$.\n", + "\n", + "The idea is now to approximate the gradient by replacing the sum over\n", + "all data points with a sum over the data points in one the minibatches\n", + "picked at random in each gradient descent step" + ] + }, + { + "cell_type": "markdown", + "id": "75d84b18", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\nabla_{\\beta}\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n", + "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0cf6f343", + "metadata": { + "editable": true + }, + "source": [ + "## The gradient step\n", + "\n", + "Thus a gradient descent step now looks like" + ] + }, + { + "cell_type": "markdown", + "id": "44f85de2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta})\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "92851949", + "metadata": { + "editable": true + }, + "source": [ + "where $k$ is picked at random with equal\n", + "probability from $[1,n/M]$. An iteration over the number of\n", + "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", + "typical to choose a number of epochs and for each epoch iterate over\n", + "the number of minibatches, as exemplified in the code below." + ] + }, + { + "cell_type": "markdown", + "id": "21d2691e", + "metadata": { + "editable": true + }, + "source": [ + "## Simple example code" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "6536b711", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 10 #number of epochs\n", + "\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for \n", + " j += 1" + ] + }, + { + "cell_type": "markdown", + "id": "4005ce6c", + "metadata": { + "editable": true + }, + "source": [ + "Taking the gradient only on a subset of the data has two important\n", + "benefits. First, it introduces randomness which decreases the chance\n", + "that our opmization scheme gets stuck in a local minima. Second, if\n", + "the size of the minibatches are small relative to the number of\n", + "datapoints ($M < n$), the computation of the gradient is much\n", + "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", + "all $n$ datapoints." + ] + }, + { + "cell_type": "markdown", + "id": "adec9808", + "metadata": { + "editable": true + }, + "source": [ + "## When do we stop?\n", + "\n", + "A natural question is when do we stop the search for a new minimum?\n", + "One possibility is to compute the full gradient after a given number\n", + "of epochs and check if the norm of the gradient is smaller than some\n", + "threshold and stop if true. However, the condition that the gradient\n", + "is zero is valid also for local minima, so this would only tell us\n", + "that we are close to a local/global minimum. However, we could also\n", + "evaluate the cost function at this point, store the result and\n", + "continue the search. If the test kicks in at a later stage we can\n", + "compare the values of the cost function and keep the $\\beta$ that\n", + "gave the lowest value." + ] + }, + { + "cell_type": "markdown", + "id": "deecc226", + "metadata": { + "editable": true + }, + "source": [ + "## Slightly different approach\n", + "\n", + "Another approach is to let the step length $\\gamma_j$ depend on the\n", + "number of epochs in such a way that it becomes very small after a\n", + "reasonable time such that we do not move at all. Such approaches are\n", + "also called scaling. There are many such ways to [scale the learning\n", + "rate](https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1)\n", + "and [discussions here](https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf). See\n", + "also\n", + "\n", + "for a discussion of different scaling functions for the learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "73685769", + "metadata": { + "editable": true + }, + "source": [ + "## Time decay rate\n", + "\n", + "As an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", + "\n", + "In this way we can fix the number of epochs, compute $\\beta$ and\n", + "evaluate the cost function at the end. Repeating the computation will\n", + "give a different result since the scheme is random by design. Then we\n", + "pick the final $\\beta$ that gives the lowest value of the cost\n", + "function." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "6484bffa", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "\n", + "def step_length(t,t0,t1):\n", + " return t0/(t+t1)\n", + "\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 500 #number of epochs\n", + "t0 = 1.0\n", + "t1 = 10\n", + "\n", + "gamma_j = t0/t1\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for beta\n", + " t = epoch*m+i\n", + " gamma_j = step_length(t,t0,t1)\n", + " j += 1\n", + "\n", + "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" + ] + }, + { + "cell_type": "markdown", + "id": "2438f642", + "metadata": { + "editable": true + }, + "source": [ + "## Code with a Number of Minibatches which varies\n", + "\n", + "In the code here we vary the number of mini-batches." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "8d624cf1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "6e9eb916", + "metadata": { + "editable": true + }, + "source": [ + "## Replace or not\n", + "\n", + "In the above code, we have use replacement in setting up the\n", + "mini-batches. The discussion\n", + "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", + "useful." + ] + }, + { + "cell_type": "markdown", + "id": "c60a0137", + "metadata": { + "editable": true + }, + "source": [ + "## Momentum based GD\n", + "\n", + "The stochastic gradient descent (SGD) is almost always used with a\n", + "*momentum* or inertia term that serves as a memory of the direction we\n", + "are moving in parameter space. This is typically implemented as\n", + "follows" + ] + }, + { + "cell_type": "markdown", + "id": "2d8174d4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "afc41240", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e3c96a9f", + "metadata": { + "editable": true + }, + "source": [ + "where we have introduced a momentum parameter $\\gamma$, with\n", + "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", + "indicate the gradient is to be taken over a different mini-batch at\n", + "each step. We call this algorithm gradient descent with momentum\n", + "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", + "running average of recently encountered gradients and\n", + "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", + "used in the averaging procedure. Consistent with this, when\n", + "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", + "earlier. An equivalent way of writing the updates is" + ] + }, + { + "cell_type": "markdown", + "id": "74e0e345", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "288fcc66", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." + ] + }, + { + "cell_type": "markdown", + "id": "63b49aca", + "metadata": { + "editable": true + }, + "source": [ + "## More on momentum based approaches\n", + "\n", + "Let us try to get more intuition from these equations. It is helpful\n", + "to consider a simple physical analogy with a particle of mass $m$\n", + "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", + "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n", + "then its motion is described by" + ] + }, + { + "cell_type": "markdown", + "id": "94b37496", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3a439485", + "metadata": { + "editable": true + }, + "source": [ + "We can discretize this equation in the usual way to get" + ] + }, + { + "cell_type": "markdown", + "id": "ff92e318", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "142e0f95", + "metadata": { + "editable": true + }, + "source": [ + "Rearranging this equation, we can rewrite this as" + ] + }, + { + "cell_type": "markdown", + "id": "88d4ce9a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5c662618", + "metadata": { + "editable": true + }, + "source": [ + "## Momentum parameter\n", + "\n", + "Notice that this equation is identical to previous one if we identify\n", + "the position of the particle, $\\mathbf{w}$, with the parameters\n", + "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n", + "parameter and learning rate with the mass of the particle and the\n", + "viscous drag as:" + ] + }, + { + "cell_type": "markdown", + "id": "2c4a2172", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "630c69f8", + "metadata": { + "editable": true + }, + "source": [ + "Thus, as the name suggests, the momentum parameter is proportional to\n", + "the mass of the particle and effectively provides inertia.\n", + "Furthermore, in the large viscosity/small learning rate limit, our\n", + "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", + "\n", + "Why is momentum useful? SGD momentum helps the gradient descent\n", + "algorithm gain speed in directions with persistent but small gradients\n", + "even in the presence of stochasticity, while suppressing oscillations\n", + "in high-curvature directions. This becomes especially important in\n", + "situations where the landscape is shallow and flat in some directions\n", + "and narrow and steep in others. It has been argued that first-order\n", + "methods (with appropriate initial conditions) can perform comparable\n", + "to more expensive second order methods, especially in the context of\n", + "complex deep learning models.\n", + "\n", + "These beneficial properties of momentum can sometimes become even more\n", + "pronounced by using a slight modification of the classical momentum\n", + "algorithm called Nesterov Accelerated Gradient (NAG).\n", + "\n", + "In the NAG algorithm, rather than calculating the gradient at the\n", + "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n", + "calculates the gradient at the expected value of the parameters given\n", + "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n", + "\\mathbf{v}_{t-1})$. This yields the NAG update rule" + ] + }, + { + "cell_type": "markdown", + "id": "7fc49052", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "800856ba", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", + "\\label{_auto2} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "154d4907", + "metadata": { + "editable": true + }, + "source": [ + "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$." + ] + }, + { + "cell_type": "markdown", + "id": "17557243", + "metadata": { + "editable": true + }, + "source": [ + "## Second moment of the gradient\n", + "\n", + "In stochastic gradient descent, with and without momentum, we still\n", + "have to specify a schedule for tuning the learning rates $\\eta_t$\n", + "as a function of time. As discussed in the context of Newton's\n", + "method, this presents a number of dilemmas. The learning rate is\n", + "limited by the steepest direction which can change depending on the\n", + "current position in the landscape. To circumvent this problem, ideally\n", + "our algorithm would keep track of curvature and take large steps in\n", + "shallow, flat directions and small steps in steep, narrow directions.\n", + "Second-order methods accomplish this by calculating or approximating\n", + "the Hessian and normalizing the learning rate by the\n", + "curvature. However, this is very computationally expensive for\n", + "extremely large models. Ideally, we would like to be able to\n", + "adaptively change the step size to match the landscape without paying\n", + "the steep computational price of calculating or approximating\n", + "Hessians.\n", + "\n", + "Recently, a number of methods have been introduced that accomplish\n", + "this by tracking not only the gradient, but also the second moment of\n", + "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", + "[ADAM](https://arxiv.org/abs/1412.6980)." + ] + }, + { + "cell_type": "markdown", + "id": "f3d09840", + "metadata": { + "editable": true + }, + "source": [ + "## RMS prop\n", + "\n", + "In RMS prop, in addition to keeping a running average of the first\n", + "moment of the gradient, we also keep track of the second moment\n", + "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n", + "for RMS prop is given by" + ] + }, + { + "cell_type": "markdown", + "id": "175455a1", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto3} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cf1e9538", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "da9b6589", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cbc7a25f", + "metadata": { + "editable": true + }, + "source": [ + "where $\\beta$ controls the averaging time of the second moment and is\n", + "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", + "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n", + "small regularization constant to prevent divergences. Multiplication\n", + "and division by vectors is understood as an element-wise operation. It\n", + "is clear from this formula that the learning rate is reduced in\n", + "directions where the norm of the gradient is consistently large. This\n", + "greatly speeds up the convergence by allowing us to use a larger\n", + "learning rate for flat directions." + ] + }, + { + "cell_type": "markdown", + "id": "e8064f4a", + "metadata": { + "editable": true + }, + "source": [ + "## [ADAM optimizer](https://arxiv.org/abs/1412.6980)\n", + "\n", + "A related algorithm is the ADAM optimizer. In\n", + "[ADAM](https://arxiv.org/abs/1412.6980), we keep a running average of\n", + "both the first and second moment of the gradient and use this\n", + "information to adaptively change the learning rate for different\n", + "parameters. The method isefficient when working with large\n", + "problems involving lots data and/or parameters. It is a combination of the\n", + "gradient descent with momentum algorithm and the RMSprop algorithm\n", + "discussed above.\n", + "\n", + "In addition to keeping a running average of the first and\n", + "second moments of the gradient\n", + "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n", + "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n", + "performs an additional bias correction to account for the fact that we\n", + "are estimating the first two moments of the gradient using a running\n", + "average (denoted by the hats in the update rule below). The update\n", + "rule for ADAM is given by (where multiplication and division are once\n", + "again understood to be element-wise operations below)" + ] + }, + { + "cell_type": "markdown", + "id": "12912817", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto4} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7864ca89", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "02a5d4ef", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "327a1f34", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c5ac526b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e6a33564", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4ffe0088", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
    \n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\label{_auto5} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "34eb03fb", + "metadata": { + "editable": true + }, + "source": [ + "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", + "second moment and are typically taken to be $0.9$ and $0.99$\n", + "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", + "\n", + "Like in RMSprop, the effective step size of a parameter depends on the\n", + "magnitude of its gradient squared. To understand this better, let us\n", + "rewrite this expression in terms of the variance\n", + "$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n", + "(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n", + "update rule for this parameter is given by" + ] + }, + { + "cell_type": "markdown", + "id": "18f62c05", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5539d5a5", + "metadata": { + "editable": true + }, + "source": [ + "## Algorithms and codes for Adagrad, RMSprop and Adam\n", + "\n", + "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", + "\n", + "The codes which implement these algorithms are discussed below here." + ] + }, + { + "cell_type": "markdown", + "id": "ae04cfe0", + "metadata": { + "editable": true + }, + "source": [ + "## Practical tips\n", + "\n", + "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", + "\n", + "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", + "\n", + "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", + "\n", + "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications." + ] + }, + { + "cell_type": "markdown", + "id": "3ffaaf9a", + "metadata": { + "editable": true + }, + "source": [ + "## Sneaking in automatic differentiation using Autograd\n", + "\n", + "We anticipate our discussions to come in connection with neural networks and automatic differentiation\n", + "by showing how we can use **autograd** for the cases above. Later we will replace **autograd** with **JAX**." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "51503c7d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "67d85da7", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "586da287", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x#+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 30\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "# Now improve with momentum gradient descent\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "for iter in range(Niterations):\n", + " # calculate gradient\n", + " gradients = training_gradient(theta)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd wth momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "b0d53639", + "metadata": { + "editable": true + }, + "source": [ + "## But none of these can compete with Newton's method" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "81089279", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Newton's method\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(beta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "# Note that here the Hessian does not depend on the parameters beta\n", + "invH = np.linalg.pinv(H)\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "beta = np.random.randn(2,1)\n", + "Niterations = 5\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(beta)\n", + " beta -= invH @ gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"beta from own Newton code\")\n", + "print(beta)" + ] + }, + { + "cell_type": "markdown", + "id": "e302b6c8", + "metadata": { + "editable": true + }, + "source": [ + "## Including Stochastic Gradient Descent with Autograd\n", + "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "88efb71c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "a3e14887", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "607e3bc9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 100\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "\n", + "for epoch in range(n_epochs):\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + "print(\"theta from own sdg with momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "d96e1c2c", + "metadata": { + "editable": true + }, + "source": [ + "## Similar (second order function now) problem but now with AdaGrad" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "6cbe854b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " Giter += gradients*gradients\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + " theta -= update\n", + "print(\"theta from own AdaGrad\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "0ed15b7b", + "metadata": { + "editable": true + }, + "source": [ + "Running this code we note an almost perfect agreement with the results from matrix inversion." + ] + }, + { + "cell_type": "markdown", + "id": "d97ab879", + "metadata": { + "editable": true + }, + "source": [ + "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "c58a19a2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameter rho\n", + "rho = 0.99\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + "\t# Accumulated gradient\n", + "\t# Scaling with rho the new and the previous results\n", + " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", + "\t# Taking the diagonal only and inverting\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + "\t# Hadamard product\n", + " theta -= update\n", + "print(\"theta from own RMSprop\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "d7106089", + "metadata": { + "editable": true + }, + "source": [ + "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "d3b9cdb9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", + "beta1 = 0.9\n", + "beta2 = 0.999\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-7\n", + "iter = 0\n", + "for epoch in range(n_epochs):\n", + " first_moment = 0.0\n", + " second_moment = 0.0\n", + " iter += 1\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " # Computing moments first\n", + " first_moment = beta1*first_moment + (1-beta1)*gradients\n", + " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", + " first_term = first_moment/(1.0-beta1**iter)\n", + " second_term = second_moment/(1.0-beta2**iter)\n", + "\t# Scaling with rho the new and the previous results\n", + " update = eta*first_term/(np.sqrt(second_term)+delta)\n", + " theta -= update\n", + "print(\"theta from own ADAM\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "e6a7abff", + "metadata": { + "editable": true + }, + "source": [ + "## Material for the lab sessions\n", + "\n", + "**Material for the lab sessions on Tuesday and Wednesday.**\n", + "\n", + "1. Exercise set for week 37\n", + "\n", + "2. Work on project 1\n", + "\n", + "\n", + " * For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/src/week37/week37.do.txt b/doc/src/week37/week37.do.txt index e942a81d5..fc160fb0e 100644 --- a/doc/src/week37/week37.do.txt +++ b/doc/src/week37/week37.do.txt @@ -9,24 +9,1500 @@ DATE: September 8-12, 2025 ===== Plans for week 37, lecture Monday ===== -!bblock Material for the lecture on Monday September 8 +!bblock Plans and material for the lecture on Monday September 8 +The family of gradient descent methods +o Plain gradient descent (constant learning rate), reminder from last week with examples using OLS and Ridge +o Improving gradient descent with momentum +o Introducing stochastic gradient descent +o More advanced updates of the learning rate: ADAgrad, RMSprop and ADAM # * "Video of Lecture":"https://youtu.be/omLmp_kkie0" # * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember9.pdf" - * Statistical interpretation of Ridge and Lasso regression, see also slides from last week - * Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well. - * Readings and Videos: - * Raschka et al, pages 175-192 - * Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). See URL:"https://link.springer.com/book/10.1007/978-0-387-84858-7". - * "Video on cross validation":"https://www.youtube.com/watch?v=fSytzGwwBVw" - * "Video on Bootstrapping":"https://www.youtube.com/watch?v=Xz0x-8-cgaQ" - * "Video on bias-variance tradeoff":"https://www.youtube.com/watch?v=EuBBz3bI-aA" +!eblock +!split +===== Readings and Videos: ===== +!bblock +o Recommended: Goodfellow et al, Deep Learning, introduction to gradient descent, see sections 4.3-4.5 at URL:"https://www.deeplearningbook.org/contents/numerical.html" and chapter 8.3-8.5 at URL::https://www.deeplearningbook.org/contents/optimization.html" +o Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression. +o Video on gradient descent at URL:"https://www.youtube.com/watch?v=sDv4f4s2SB8" +o Video on Stochastic gradient descent at URL:"https://www.youtube.com/watch?v=vMh0zPT0tLI" !eblock + + + + !split -===== Plans for week 37, lab sessions ===== +===== Material for lecture Monday September 8 ===== + + + + + + + + +!split +===== Gradient descent and revisiting Ordinary Least Squares from last week ===== + +Last week we started with linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: + +o An analytical solution (recall homework sets for week 35). +o The gradient can be computed analytically. +o The cost function is convex which guarantees that gradient descent converges for small enough learning rates + +We revisit an example similar to what we had in the first homework set. We have a function of the type + +!bc pycod +x = 2*np.random.rand(m,1) +y = 4+3*x+np.random.randn(m,1) +!ec +with $x_i \in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\cal {N}(0,1)$. +The linear regression model is given by +!bt +\[ +h_\theta(x) = \bm{y} = \theta_0 + \theta_1 x, +\] +!et +such that +!bt +\[ +\bm{y}_i = \theta_0 + \theta_1 x_i. +\] +!et + +!split +===== Gradient descent example ===== + +Let $\mathbf{y} = (y_1,\cdots,y_n)^T$, $\mathbf{\bm{y}} = (\bm{y}_1,\cdots,\bm{y}_n)^T$ and $\theta = (\theta_0, \theta_1)^T$ + +It is convenient to write $\mathbf{\bm{y}} = X\theta$ where $X \in \mathbb{R}^{100 \times 2} $ is the design matrix given by (we keep the intercept here) +!bt +\[ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +\] +!et +The cost/loss/risk function is given by ( +!bt +\[ +C(\theta) = \frac{1}{n}||X\theta-\mathbf{y}||_{2}^{2} = \frac{1}{n}\sum_{i=1}^{100}\left[ (\theta_0 + \theta_1 x_i)^2 - 2 y_i (\theta_0 + \theta_1 x_i) + y_i^2\right] +\] +!et +and we want to find $\theta$ such that $C(\theta)$ is minimized. + +!split +===== The derivative of the cost/loss function ===== + +Computing $\partial C(\theta) / \partial \theta_0$ and $\partial C(\theta) / \partial \theta_1$ we can show that the gradient can be written as +!bt +\[ +\nabla_{\theta} C(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = \frac{2}{n}X^T(X\theta - \mathbf{y}), +\] +!et +where $X$ is the design matrix defined above. + +!split +===== The Hessian matrix ===== +The Hessian matrix of $C(\theta)$ is given by +!bt +\[ +\bm{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X. +\] +!et +This result implies that $C(\theta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite. + + + + +!split +===== Simple program ===== + +We can now write a program that minimizes $C(\theta)$ using the gradient descent method with a constant learning rate $\gamma$ according to +!bt +\[ +\theta_{k+1} = \theta_k - \gamma \nabla_\theta C(\theta_k), \ k=0,1,\cdots +\] +!et + +We can use the expression we computed for the gradient and let use a +$\theta_0$ be chosen randomly and let $\gamma = 0.001$. Stop iterating +when $||\nabla_\theta C(\theta_k) || \leq \epsilon = 10^{-8}$. _Note that the code below does not include the latter stop criterion_. + +And finally we can compare our solution for $\theta$ with the analytic result given by +$\theta= (X^TX)^{-1} X^T \mathbf{y}$. + +!split +===== Gradient Descent Example ===== + +Here our simple example +!bc pycod + +# Importing various packages +from random import random, seed +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm +from matplotlib.ticker import LinearLocator, FormatStrFormatter +import sys + +# the number of datapoints +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +# Hessian matrix +H = (2.0/n)* X.T @ X +# Get the eigenvalues +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y +print(theta_linreg) +theta = np.random.randn(2,1) + +eta = 1.0/np.max(EigValues) +Niterations = 1000 + +for iter in range(Niterations): + gradient = (2.0/n)*X.T @ (X @ theta-y) + theta -= eta*gradient + +print(theta) +xnew = np.array([[0],[2]]) +xbnew = np.c_[np.ones((2,1)), xnew] +ypredict = xbnew.dot(theta) +ypredict2 = xbnew.dot(theta_linreg) +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Gradient descent example') +plt.show() + +!ec + + +!split +===== Gradient descent and Ridge ===== + +We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\theta$, +!bt +\[ +C_{\text{ridge}}(\theta) = \frac{1}{n}||X\theta -\mathbf{y}||^2 + \lambda ||\theta||^2, \ \lambda \geq 0. +\] +!et + +In order to minimize $C_{\text{ridge}}(\theta)$ using GD we adjust the gradient as follows +!bt +\[ +\nabla_\theta C_{\text{ridge}}(\theta) = \frac{2}{n}\begin{bmatrix} \sum_{i=1}^{100} \left(\theta_0+\theta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\theta_0+\theta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \theta_0 \\ \theta_1\end{bmatrix} = 2 (\frac{1}{n}X^T(X\theta - \mathbf{y})+\lambda \theta). +\] +!et + +We can easily extend our program to minimize $C_{\text{ridge}}(\theta)$ using gradient descent and compare with the analytical solution given by +!bt +\[ +\theta_{\text{ridge}} = \left(X^T X + n\lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +\] +!et + +!split +===== The Hessian matrix for Ridge Regression ===== +The Hessian matrix of Ridge Regression for our simple example is given by +!bt +\[ +\bm{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\theta)}{\partial \theta_0^2} & \frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} \\ +\frac{\partial^2 C(\theta)}{\partial \theta_0 \partial \theta_1} & \frac{\partial^2 C(\theta)}{\partial \theta_1^2} & \\ +\end{bmatrix} = \frac{2}{n}X^T X+2\lambda\bm{I}. +\] +!et +This implies that the Hessian matrix is positive definite, hence the stationary point is a +minimum. +Note that the Ridge cost function is convex being a sum of two convex +functions. Therefore, the stationary point is a global +minimum of this function. + + +!split +===== Program example for gradient descent with Ridge Regression ===== +!bc pycod +from random import random, seed +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm +from matplotlib.ticker import LinearLocator, FormatStrFormatter +import sys + +# the number of datapoints +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X + +#Ridge parameter lambda +lmbda = 0.001 +Id = n*lmbda* np.eye(XT_X.shape[0]) + +# Hessian matrix +H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0]) +# Get the eigenvalues +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + + +theta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y +print(theta_linreg) +# Start plain gradient descent +theta = np.random.randn(2,1) + +eta = 1.0/np.max(EigValues) +Niterations = 100 + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ (X @ (theta)-y)+2*lmbda*theta + theta -= eta*gradients + +print(theta) +ypredict = X @ theta +ypredict2 = X @ theta_linreg +plt.plot(x, ypredict, "r-") +plt.plot(x, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Gradient descent example for Ridge') +plt.show() +!ec + + + +!split +===== Using gradient descent methods, limitations ===== + +* _Gradient descent (GD) finds local minima of our function_. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance. + +* _GD is sensitive to initial conditions_. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD. + +* _Gradients are computationally expensive to calculate for large datasets_. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called ``mini batches''. This has the added benefit of introducing stochasticity into our algorithm. + +* _GD is very sensitive to choices of learning rates_. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape. + +* _GD treats all directions in parameter space uniformly._ Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. + +* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points. + + + +!split +===== Improving gradient descent with momentum ===== + +We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent. + +!bc pycod +from numpy import asarray +from numpy import arange +from numpy.random import rand +from numpy.random import seed +from matplotlib import pyplot + +# objective function +def objective(x): + return x**2.0 + +# derivative of objective function +def derivative(x): + return x * 2.0 + +# gradient descent algorithm +def gradient_descent(objective, derivative, bounds, n_iter, step_size): + # track all solutions + solutions, scores = list(), list() + # generate an initial point + solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) + # run the gradient descent + for i in range(n_iter): + # calculate gradient + gradient = derivative(solution) + # take a step + solution = solution - step_size * gradient + # evaluate candidate point + solution_eval = objective(solution) + # store solution + solutions.append(solution) + scores.append(solution_eval) + # report progress + print('>%d f(%s) = %.5f' % (i, solution, solution_eval)) + return [solutions, scores] + +# seed the pseudo random number generator +seed(4) +# define range for input +bounds = asarray([[-1.0, 1.0]]) +# define the total iterations +n_iter = 30 +# define the step size +step_size = 0.1 +# perform the gradient descent search +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size) +# sample input range uniformly at 0.1 increments +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1) +# compute targets +results = objective(inputs) +# create a line plot of input vs result +pyplot.plot(inputs, results) +# plot the solutions found +pyplot.plot(solutions, scores, '.-', color='red') +# show the plot +pyplot.show() + +!ec + + +!split +===== Same code but now with momentum gradient descent ===== + +!bc pycod +from numpy import asarray +from numpy import arange +from numpy.random import rand +from numpy.random import seed +from matplotlib import pyplot + +# objective function +def objective(x): + return x**2.0 + +# derivative of objective function +def derivative(x): + return x * 2.0 + +# gradient descent algorithm +def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum): + # track all solutions + solutions, scores = list(), list() + # generate an initial point + solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) + # keep track of the change + change = 0.0 + # run the gradient descent + for i in range(n_iter): + # calculate gradient + gradient = derivative(solution) + # calculate update + new_change = step_size * gradient + momentum * change + # take a step + solution = solution - new_change + # save the change + change = new_change + # evaluate candidate point + solution_eval = objective(solution) + # store solution + solutions.append(solution) + scores.append(solution_eval) + # report progress + print('>%d f(%s) = %.5f' % (i, solution, solution_eval)) + return [solutions, scores] + +# seed the pseudo random number generator +seed(4) +# define range for input +bounds = asarray([[-1.0, 1.0]]) +# define the total iterations +n_iter = 30 +# define the step size +step_size = 0.1 +# define momentum +momentum = 0.3 +# perform the gradient descent search with momentum +solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum) +# sample input range uniformly at 0.1 increments +inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1) +# compute targets +results = objective(inputs) +# create a line plot of input vs result +pyplot.plot(inputs, results) +# plot the solutions found +pyplot.plot(solutions, scores, '.-', color='red') +# show the plot +pyplot.show() +!ec + + + +!split +===== Overview video on Stochastic Gradient Descent ===== + +"What is Stochastic Gradient Descent":"https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer" + + +!split +===== Batches and mini-batches ===== + +In gradient descent we compute the cost function and its gradient for all data points we have. + +In large-scale applications such as the "ILSVRC challenge":"https://www.image-net.org/challenges/LSVRC/", the +training data can have on order of millions of examples. Hence, it +seems wasteful to compute the full cost function over the entire +training set in order to perform only a single parameter update. A +very common approach to addressing this challenge is to compute the +gradient over batches of the training data. For example, a typical batch could contain some thousand examples from +an entire training set of several millions. This batch is then used to +perform a parameter update. + +!split +===== Stochastic Gradient Descent (SGD) ===== + +In stochastic gradient descent, the extreme case is the case where we +have only one batch, that is we include the whole data set. + +This process is called Stochastic Gradient +Descent (SGD) (or also sometimes on-line gradient descent). This is +relatively less common to see because in practice due to vectorized +code optimizations it can be computationally much more efficient to +evaluate the gradient for 100 examples, than the gradient for one +example 100 times. Even though SGD technically refers to using a +single example at a time to evaluate the gradient, you will hear +people use the term SGD even when referring to mini-batch gradient +descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD +for “Batch gradient descent” are rare to see), where it is usually +assumed that mini-batches are used. The size of the mini-batch is a +hyperparameter but it is not very common to cross-validate or bootstrap it. It is +usually based on memory constraints (if any), or set to some value, +e.g. 32, 64 or 128. We use powers of 2 in practice because many +vectorized operation implementations work faster when their inputs are +sized in powers of 2. + +In our notes with SGD we mean stochastic gradient descent with mini-batches. + + +!split +===== Stochastic Gradient Descent ===== + +Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over $n$ data points $\{\mathbf{x}_i\}_{i=1}^n$, +!bt +\[ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +\] +!et + +!split +===== Computation of gradients ===== + +This in turn means that the gradient can be +computed as a sum over $i$-gradients +!bt +\[ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +\] +!et + +Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are $n$ +data points and the size of each minibatch is $M$, there will be $n/M$ +minibatches. We denote these minibatches by $B_k$ where +$k=1,\cdots,n/M$. + + + +!split +===== SGD example ===== +As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$ +and we choose to have $M=5$ minibathces, +then each minibatch contains two data points. In particular we have +$B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10})$. Note that if you choose $M=1$ you +have only a single batch with all data points and on the other extreme, +you may choose $M=n$ resulting in a minibatch for each datapoint, i.e +$B_k = \mathbf{x}_k$. + +The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +!bt +\[ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +\] +!et + +!split +===== The gradient step ===== + +Thus a gradient descent step now looks like +!bt +\[ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +\] +!et + +where $k$ is picked at random with equal +probability from $[1,n/M]$. An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. + +!split +===== Simple example code ===== + +!bc pycod +import numpy as np + +n = 100 #100 datapoints +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +n_epochs = 10 #number of epochs + +j = 0 +for epoch in range(1,n_epochs+1): + for i in range(m): + k = np.random.randint(m) #Pick the k-th minibatch at random + #Compute the gradient using the data in minibatch Bk + #Compute new suggestion for + j += 1 +!ec + +Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints ($M < n$), the computation of the gradient is much +cheaper since we sum over the datapoints in the $k-th$ minibatch and not +all $n$ datapoints. + +!split +===== When do we stop? ===== + +A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the $\beta$ that +gave the lowest value. + +!split +===== Slightly different approach ===== + +Another approach is to let the step length $\gamma_j$ depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. Such approaches are +also called scaling. There are many such ways to "scale the learning +rate":"https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1" +and "discussions here":"https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf". See +also +URL:"https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1" +for a discussion of different scaling functions for the learning rate. + +!split +===== Time decay rate ===== + +As an example, let $e = 0,1,2,3,\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \cdot m + i$ where $m$ is the number of minibatches and $i=0,\cdots,m-1$. Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$. + +In this way we can fix the number of epochs, compute $\beta$ and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final $\beta$ that gives the lowest value of the cost +function. + +!bc pycod +import numpy as np + +def step_length(t,t0,t1): + return t0/(t+t1) + +n = 100 #100 datapoints +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +n_epochs = 500 #number of epochs +t0 = 1.0 +t1 = 10 + +gamma_j = t0/t1 +j = 0 +for epoch in range(1,n_epochs+1): + for i in range(m): + k = np.random.randint(m) #Pick the k-th minibatch at random + #Compute the gradient using the data in minibatch Bk + #Compute new suggestion for beta + t = epoch*m+i + gamma_j = step_length(t,t0,t1) + j += 1 + +print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j)) +!ec + + + + + + +!split +===== Code with a Number of Minibatches which varies ===== + +In the code here we vary the number of mini-batches. +!bc pycode +# Importing various packages +from math import exp, sqrt +from random import random, seed +import numpy as np +import matplotlib.pyplot as plt + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + + +for iter in range(Niterations): + gradients = 2.0/n*X.T @ ((X @ theta)-y) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 + +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +!ec + + + +!split +===== Replace or not ===== + +In the above code, we have use replacement in setting up the +mini-batches. The discussion +"here":"https://sebastianraschka.com/faq/docs/sgd-methods.html" may be +useful. + + +!split +===== Momentum based GD ===== + +The stochastic gradient descent (SGD) is almost always used with a +*momentum* or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +!bt +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\end{align} +!et + +where we have introduced a momentum parameter $\gamma$, with +$0\le\gamma\le 1$, and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that $\mathbf{v}_t$ is a +running average of recently encountered gradients and +$(1-\gamma)^{-1}$ sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +$\gamma=0$, this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +!bt +\[ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +\] +!et +where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$. + +!split +===== More on momentum based approaches ===== + +Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass $m$ +moving in a viscous medium with drag coefficient $\mu$ and potential +$E(\mathbf{w})$. If we denote the particle's position by $\mathbf{w}$, +then its motion is described by + +!bt +\[ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +\] +!et + +We can discretize this equation in the usual way to get + +!bt +\[ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +\] +!et + +Rearranging this equation, we can rewrite this as + +!bt +\[ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +\] +!et + +!split +===== Momentum parameter ===== + +Notice that this equation is identical to previous one if we identify +the position of the particle, $\mathbf{w}$, with the parameters +$\boldsymbol{\theta}$. This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: + +!bt +\[ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +\] +!et + +Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as $(1-\gamma)^{-1} \approx m/(\mu \Delta t)$. + +Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. + +These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). + +In the NAG algorithm, rather than calculating the gradient at the +current parameters, $\nabla_\theta E(\boldsymbol{\theta}_t)$, one +calculates the gradient at the expected value of the parameters given +our current momentum, $\nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1})$. This yields the NAG update rule + +!bt +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\end{align} +!et + +One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\gamma$. + + +!split +===== Second moment of the gradient ===== + + +In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates $\eta_t$ +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. + +Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and +"ADAM":"https://arxiv.org/abs/1412.6980". + +!split +===== RMS prop ===== + +In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by $\mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2]$. The update rule +for RMS prop is given by + +!bt +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +!et + +where $\beta$ controls the averaging time of the second moment and is +typically taken to be about $\beta=0.9$, $\eta_t$ is a learning rate +typically chosen to be $10^{-3}$, and $\epsilon\sim 10^{-8} $ is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. + + +!split +===== "ADAM optimizer":"https://arxiv.org/abs/1412.6980" ===== + +A related algorithm is the ADAM optimizer. In +"ADAM":"https://arxiv.org/abs/1412.6980", we keep a running average of +both the first and second moment of the gradient and use this +information to adaptively change the learning rate for different +parameters. The method isefficient when working with large +problems involving lots data and/or parameters. It is a combination of the +gradient descent with momentum algorithm and the RMSprop algorithm +discussed above. + +In addition to keeping a running average of the first and +second moments of the gradient +(i.e. $\mathbf{m}_t=\mathbb{E}[\mathbf{g}_t]$ and +$\mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t]$, respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +!bt +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\bm{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\bm{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \bm{\mathbf{m}}_t \over \sqrt{\bm{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\end{align} +!et + +where $\beta_1$ and $\beta_2$ set the memory lifetime of the first and +second moment and are typically taken to be $0.9$ and $0.99$ +respectively, and $\eta$ and $\epsilon$ are identical to RMSprop. + +Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +$\boldsymbol{\sigma}_t^2 = \bm{\mathbf{s}}_t - +(\bm{\mathbf{m}}_t)^2$. Consider a single parameter $\theta_t$. The +update rule for this parameter is given by + +!bt +\[ +\Delta \theta_{t+1}= -\eta_t { \bm{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +\] +!et + +!split +===== Algorithms and codes for Adagrad, RMSprop and Adam ===== + +The algorithms we have implemented are well described in the text by "Goodfellow, Bengio and Courville, chapter 8":"https://www.deeplearningbook.org/contents/optimization.html". + +The codes which implement these algorithms are discussed below here. + + +!split +===== Practical tips ===== + +* _Randomize the data when making mini-batches_. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented. + +* _Transform your inputs_. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case. + +* _Monitor the out-of-sample performance._ Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings. + +* _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. + + + + + +!split +===== Sneaking in automatic differentiation using Autograd ===== + +We anticipate our discussions to come in connection with neural networks and automatic differentiation +by showing how we can use _autograd_ for the cases above. Later we will replace _autograd_ with _JAX_. + + +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +!ec + + +!split +===== Same code but now with momentum gradient descent ===== +!bc pycod +# Using Autograd to calculate gradients for OLS +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x#+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 30 + +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(theta) + theta -= eta*gradients + print(iter,gradients[0],gradients[1]) +print("theta from own gd") +print(theta) + +# Now improve with momentum gradient descent +change = 0.0 +delta_momentum = 0.3 +for iter in range(Niterations): + # calculate gradient + gradients = training_gradient(theta) + # calculate update + new_change = eta*gradients+delta_momentum*change + # take a step + theta -= new_change + # save the change + change = new_change + print(iter,gradients[0],gradients[1]) +print("theta from own gd wth momentum") +print(theta) + +!ec + +!split +===== But none of these can compete with Newton's method ===== + +!bc pycod +# Using Newton's method +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +def CostOLS(beta): + return (1.0/n)*np.sum((y-X @ beta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(beta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +# Note that here the Hessian does not depend on the parameters beta +invH = np.linalg.pinv(H) +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +beta = np.random.randn(2,1) +Niterations = 5 + +# define the gradient +training_gradient = grad(CostOLS) + +for iter in range(Niterations): + gradients = training_gradient(beta) + beta -= invH @ gradients + print(iter,gradients[0],gradients[1]) +print("beta from own Newton code") +print(beta) +!ec + + +!split +===== Including Stochastic Gradient Descent with Autograd ===== +In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using _autograd_. + +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 1000 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + +xnew = np.array([[0],[2]]) +Xnew = np.c_[np.ones((2,1)), xnew] +ypredict = Xnew.dot(theta) +ypredict2 = Xnew.dot(theta_linreg) + +plt.plot(xnew, ypredict, "r-") +plt.plot(xnew, ypredict2, "b-") +plt.plot(x, y ,'ro') +plt.axis([0,2.0,0, 15.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Random numbers ') +plt.show() + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +for epoch in range(n_epochs): +# Can you figure out a better way of setting up the contributions to each batch? + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + theta = theta - eta*gradients +print("theta from own sdg") +print(theta) + + +!ec + + +!split +===== Same code but now with momentum gradient descent ===== +!bc pycod +# Using Autograd to calculate gradients using SGD +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 100 +x = 2*np.random.rand(n,1) +y = 4+3*x+np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) +# Hessian matrix +H = (2.0/n)* XT_X +EigValues, EigVectors = np.linalg.eig(H) +print(f"Eigenvalues of Hessian Matrix:{EigValues}") + +theta = np.random.randn(2,1) +eta = 1.0/np.max(EigValues) +Niterations = 100 + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) + +for iter in range(Niterations): + gradients = (1.0/n)*training_gradient(y, X, theta) + theta -= eta*gradients +print("theta from own gd") +print(theta) + + +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +t0, t1 = 5, 50 +def learning_schedule(t): + return t0/(t+t1) + +theta = np.random.randn(2,1) + +change = 0.0 +delta_momentum = 0.3 + +for epoch in range(n_epochs): + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + eta = learning_schedule(epoch*m+i) + # calculate update + new_change = eta*gradients+delta_momentum*change + # take a step + theta -= new_change + # save the change + change = new_change +print("theta from own sdg with momentum") +print(theta) +!ec + + +!split +===== Similar (second order function now) problem but now with AdaGrad ===== +!bc pycod +# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-8 +for epoch in range(n_epochs): + Giter = 0.0 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + Giter += gradients*gradients + update = gradients*eta/(delta+np.sqrt(Giter)) + theta -= update +print("theta from own AdaGrad") +print(theta) + + +!ec + +Running this code we note an almost perfect agreement with the results from matrix inversion. + +!split +===== RMSprop for adaptive learning rate with Stochastic Gradient Descent ===== +!bc pycod +# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x# +np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Value for parameter rho +rho = 0.99 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-8 +for epoch in range(n_epochs): + Giter = 0.0 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + # Accumulated gradient + # Scaling with rho the new and the previous results + Giter = (rho*Giter+(1-rho)*gradients*gradients) + # Taking the diagonal only and inverting + update = gradients*eta/(delta+np.sqrt(Giter)) + # Hadamard product + theta -= update +print("theta from own RMSprop") +print(theta) +!ec + +!split +===== And finally "ADAM":"https://arxiv.org/pdf/1412.6980.pdf" ===== + +!bc pycod +# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent +# OLS example +from random import random, seed +import numpy as np +import autograd.numpy as np +import matplotlib.pyplot as plt +from autograd import grad + +# Note change from previous example +def CostOLS(y,X,theta): + return np.sum((y-X @ theta)**2) + +n = 1000 +x = np.random.rand(n,1) +y = 2.0+3*x +4*x*x# +np.random.randn(n,1) + +X = np.c_[np.ones((n,1)), x, x*x] +XT_X = X.T @ X +theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y) +print("Own inversion") +print(theta_linreg) + + +# Note that we request the derivative wrt third argument (theta, 2 here) +training_gradient = grad(CostOLS,2) +# Define parameters for Stochastic Gradient Descent +n_epochs = 50 +M = 5 #size of each minibatch +m = int(n/M) #number of minibatches +# Guess for unknown parameters theta +theta = np.random.randn(3,1) + +# Value for learning rate +eta = 0.01 +# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980 +beta1 = 0.9 +beta2 = 0.999 +# Including AdaGrad parameter to avoid possible division by zero +delta = 1e-7 +iter = 0 +for epoch in range(n_epochs): + first_moment = 0.0 + second_moment = 0.0 + iter += 1 + for i in range(m): + random_index = M*np.random.randint(m) + xi = X[random_index:random_index+M] + yi = y[random_index:random_index+M] + gradients = (1.0/M)*training_gradient(yi, xi, theta) + # Computing moments first + first_moment = beta1*first_moment + (1-beta1)*gradients + second_moment = beta2*second_moment+(1-beta2)*gradients*gradients + first_term = first_moment/(1.0-beta1**iter) + second_term = second_moment/(1.0-beta2**iter) + # Scaling with rho the new and the previous results + update = eta*first_term/(np.sqrt(second_term)+delta) + theta -= update +print("theta from own ADAM") +print(theta) +!ec + + +!split +===== Material for the lab sessions ===== @@ -36,1623 +1512,3 @@ o Work on project 1 # * "Video of exercise sessions week 37":"https://youtu.be/bK4AEcTu-oM" * For more discussions of Ridge regression and calculation of averages, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. !eblock - - - - -!split -===== Material for lecture Monday September 8 ===== - - -!split -===== 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(\bm{x})$ and a random noise $\bm{\epsilon}$ given by the normal -distribution with zero mean value and an undetermined variance -$\sigma^2$. - -We found above that the outputs $\bm{y}$ have a mean value given by -$\bm{X}\hat{\bm{\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 $\bm{X}\hat{\bm{\beta}}$. This means that a -single output $y_i$ is given by the Gaussian distribution - -!bt -\[ -y_i\sim \mathcal{N}(\bm{X}_{i,*}\bm{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. -\] -!et - -!split -===== 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 -!bt -\[ -p(y_i, \bm{X}\vert\bm{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}, -\] -!et -which reads as finding the likelihood of an event $y_i$ with the input variables $\bm{X}$ given the parameters (to be determined) $\bm{\beta}$. - -Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\bm{y}$ as the product of the single events, that is we have - -!bt -\[ -p(\bm{y},\bm{X}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta}). -\] -!et - -We will write this in a more compact form reserving $\bm{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 -!bt -\[ -\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -\] -!et -In the more general case the various inputs should be replaced by the possible features represented by the input data set $\bm{X}$. -We can now rewrite the above probability as -!bt -\[ -p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. -\] -!et - -It is a conditional probability (see below) and reads as the likelihood of a domain of events $\bm{D}$ given a set of parameters $\bm{\beta}$. - -!split -===== 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. - - - -!split -===== A new Cost Function ===== - -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -!bt -\[ -C(\bm{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\bm{X}\vert\bm{\beta})}, -\] -!et -which becomes -!bt -\[ -C(\bm{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}. -\] -!et - -Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely - -!bt -\[ -\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right) =0, -\] -!et -which leads to the well-known OLS equation for the optimal paramters $\beta$ -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{OLS}}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}! -\] -!et - - -Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. - -!split -===== More basic Statistics and Bayes' theorem ===== - -A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. - -Assume we have two domains of events $X=[x_0,x_1,\dots,x_{n-1}]$ and $Y=[y_0,y_1,\dots,y_{n-1}]$. - -We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively. -The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. - -!bblock Union of events is given by -!bt -\[ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -\] -!et -!eblock - - -!bblock The product rule (aka joint probability) is given by -!bt -\[ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -\] -!et -where we read $p(X\vert Y)$ as the likelihood of obtaining $X$ given $Y$. -!eblock - -If we have independent events then $p(X,Y)=p(X)p(Y)$. - - -!split -===== Marginal Probability ===== - -The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have -!bblock -!bt -\[ -p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). -\] -!et -!eblock - - -!split -===== Conditional Probability ===== - -The conditional probability, if $p(Y) > 0$, is -!bblock -!bt -\[ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. -\] -!et -!eblock - - -!split -===== Bayes' Theorem ===== - -If we combine the conditional probability with the marginal probability and the standard product rule, we have -!bt -\[ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -\] -!et -which we can rewrite as - -!bt -\[ -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)}, -\] -!et -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$. - -!split -===== 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. - -Let us try to illustrate Bayes' theorem through an example. - -!split -===== Example of Usage of Bayes' theorem ===== - -Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable $X$. It takes binary -values with $X=1$ representing a positive event and $X=0$ being a -negative event. We reserve $Y$ as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). - -We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not. - -Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have - -!bt -\[ -p(X=1\vert Y=1) =0.8. -\] -!et - -This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\%$ for having cancer. -It is however not correct, as the following Bayesian analysis shows. - -!split -===== Doing it correctly ===== - -If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is - -!bt -\[ -p(Y=1) =0.004. -\] -!et - -We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have -!bt -\[ -p(X=1\vert Y=0) =0.1. -\] -!et - -Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute - -!bt -\[ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -\] -!et -That is, in case of a positive test, there is only a $3\%$ chance of having breast cancer! - - -!split -===== Bayes' Theorem and Ridge and Lasso Regression ===== - -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 $\bm{D}$ (one-dimensional case) -!bt -\[ -\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -\] -!et -is given by -!bt -\[ -p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. -\] -!et - -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 $\bm{\beta}$ given a domain of events $\bm{D}$? That is, how can we define the posterior probability - -!bt -\[ -p(\bm{\beta}\vert\bm{D}). -\] -!et - -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -!bt -\[ -p(\bm{\beta}\vert\bm{D})\propto p(\bm{D}\vert\bm{\beta})p(\bm{\beta}). -\] -!et - -We have a model for $p(\bm{D}\vert\bm{\beta})$ but need one for the _prior_ $p(\bm{\beta})$! - - -!split -===== 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 $\bm{\beta}$ and the mean value, assume that the prior for the values $\bm{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is - -!bt -\[ -p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -\] -!et - -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -!bt -\[ -p(\bm{\beta\vert\bm{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -\] -!et - - -We can now optimize this quantity with respect to $\bm{\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 - - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\bm{\beta}\vert\vert_2^2, -\] -!et -and replacing $1/2\tau^2$ with $\lambda$ we have - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_2^2, -\] -!et -which is our Ridge cost function! Nice, isn't it? - -!split -===== Lasso and Bayes ===== - -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 - -!bt -\[ -p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -\] -!et - -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -!bt -\[ -p(\bm{\beta}\vert\bm{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -\] -!et - - -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on $\beta$, we have - - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\bm{\beta}\vert\vert_1, -\] -!et -and replacing $1/\tau$ with $\lambda$ we have - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_1, -\] -!et -which is our Lasso cost function! - - - - - - -!split -===== 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 -o look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff -o introduce resampling techniques like cross-validation, bootstrapping and jackknife and more - -and discuss how to select a given model (one of the difficult parts in machine learning). - - - - - -!split -===== Resampling methods ===== -!bblock -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, -o The _bootstrap method_ -o and _Cross-Validation_ - -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. - - -!eblock - - -!split -===== Resampling approaches can be computationally expensive ===== -!bblock - -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. - -!eblock - -!split -===== Why resampling methods ? ===== -!bblock 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. - - -!eblock - -!split -===== Statistical analysis ===== -!bblock - -* 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. -!eblock - - - - - -!split -===== Resampling methods ===== - -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. - -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. - -In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, -we discuss the -o prediction error or simply the _test error_ $\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the -o training error $\mathrm{Err_{Train}}$, which is the average loss over the training data. - -As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. -For a certain level of complexity the test error will reach minimum, before starting to increase again. The -training error reaches a saturation. - - -!split -===== Resampling methods: Bootstrap ===== -!bblock -Bootstrapping is a "non-parametric approach":"https://en.wikipedia.org/wiki/Nonparametric_statistics" to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: -o The bootstrap is quite general, although there are some cases in which it fails. -o Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. -o It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. -o It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -!eblock - -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". - - -Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called _central limit theorem_. - -!split -===== The Central Limit Theorem ===== - - -Suppose we have a PDF $p(x)$ from which we generate a series $N$ -of averages $\mathbb{E}[x_i]$. Each mean value $\mathbb{E}[x_i]$ -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 $\mathbb{E}[x_i]=x_i$ in the discussion -which follows. We do the same for $\mathbb{E}[z]=z$. - -If we compute the mean $z$ of $m$ such mean values $x_i$ -!bt -\[ - z=\frac{x_1+x_2+\dots+x_m}{m}, -\] -!et -the question we pose is which is the PDF of the new variable $z$. - -!split -===== 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 -!bt -\[ - \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}), -\] -!et -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. - - -!split -===== Rewriting the $\delta$-function ===== - -If we use the integral expression for the $\delta$-function - -!bt -\[ - \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)}, -\] -!et -and inserting $e^{i\mu q-i\mu q}$ where $\mu$ is the mean value -we arrive at -!bt -\[ - \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, -\] -!et -with the integral over $x$ resulting in - -!bt -\[ - \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]. -\] -!et - -!split -===== Identifying Terms ===== - -The second term on the rhs disappears since this is just the mean and -employing the definition of $\sigma^2$ we have -!bt -\[ - \int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}= - 1-\frac{q^2\sigma^2}{2m^2}+\dots, -\] -!et -resulting in - -!bt -\[ - \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, -\] -!et -and in the limit $m\rightarrow \infty$ we obtain - -!bt -\[ - \tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})} - \exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)}, -\] -!et -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)$. - -!split -===== 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 central limit theorem leads to the well-known expression for the -standard deviation, given by - -!bt -\[ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -\] -!et - -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 (the so-called Bessel correction) -!bt -\[ - \sigma_m\approx -\frac{\sigma}{\sqrt{m-1}}. -\] -!et - -In many cases however the above estimate for the standard deviation, -in particular if correlations are strong, may be too simplistic. Keep -in mind that we have assumed that the variables $x$ are independent -and identically distributed. This is obviously not always the -case. For example, the random numbers (or better pseudorandom numbers) -we generate in various calculations do always exhibit some -correlations. - - - -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 form /analytic expression for -$\tilde{p}(x)$. - - -!split -===== Confidence Intervals ===== - -Confidence intervals are used in statistics and represent 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. - -In the exercises this week we show 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 can 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 ===== - -Since $\widehat{\beta} = \widehat{\beta}(\bm{X})$ is a function of random variables, -$\widehat{\beta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to -estimate $p(\bm{t})$ by the relative frequency of -$\widehat{\beta}$. You can think of this as using a histogram -in the place of $p(\bm{t})$. If the relative frequency closely -resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\bm{t})$ using point -estimators. - - -!split -===== Resampling methods: More Bootstrap background ===== - -In the case that $\widehat{\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: -o Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. -o Then using these numbers, we could compute a replica of $\widehat{\beta}$ called $\widehat{\beta}^*$. - -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(\bm{t})$. - -!split -===== Resampling methods: Bootstrap approach ===== - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, "Efron in 1979":"https://projecteuclid.org/euclid.aos/1176344552" asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$? - -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - - -!split -===== Resampling methods: Bootstrap steps ===== - -The independent bootstrap works like this: - -o Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. -o Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. -o Using the vector $\bm{x}^*$ compute $\widehat{\beta}^*$ by evaluating $\widehat \beta$ under the observations $\bm{x}^*$. -o Repeat this process $k$ times. - -When you are done, you can draw a histogram of the relative frequency -of $\widehat \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^*$. - - -!split -===== Code example for the Bootstrap method ===== - -The following code starts with a Gaussian distribution with mean value -$\mu =100$ and variance $\sigma=15$. We use this to generate the data -used in the bootstrap analysis. The bootstrap analysis returns a data -set after a given number of bootstrap operations (as many as we have -data points). This data set consists of estimated mean values for each -bootstrap operation. The histogram generated by the bootstrap method -shows that the distribution for these mean values is also a Gaussian, -centered around the mean value $\mu=100$ but with standard deviation -$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in -this case the same as the number of original data points). The value -of the standard deviation is what we expect from the central limit -theorem. - - -!bc pycod -import numpy as np -from time import time -from scipy.stats import norm -import matplotlib.pyplot as plt - -# Returns mean of bootstrap samples -# Bootstrap algorithm -def bootstrap(data, datapoints): - t = np.zeros(datapoints) - n = len(data) - # non-parametric bootstrap - for i in range(datapoints): - t[i] = np.mean(data[np.random.randint(0,n,n)]) - # analysis - print("Bootstrap Statistics :") - print("original bias std. error") - print("%8g %8g %14g %15g" % (np.mean(data), np.std(data),np.mean(t),np.std(t))) - return t - -# We set the mean value to 100 and the standard deviation to 15 -mu, sigma = 100, 15 -datapoints = 10000 -# We generate random numbers according to the normal distribution -x = mu + sigma*np.random.randn(datapoints) -# bootstrap returns the data sample -t = bootstrap(x, datapoints) -!ec -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. - -!split -===== Plotting the Histogram ===== -!bc pycod -# the histogram of the bootstrapped data (normalized data if density = True) -n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75) -# add a 'best fit' line -y = norm.pdf(binsboot, np.mean(t), np.std(t)) -lt = plt.plot(binsboot, y, 'b', linewidth=1) -plt.xlabel('x') -plt.ylabel('Probability') -plt.grid(True) -plt.show() -!ec - - - -!split -===== The bias-variance tradeoff ===== - - -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset $\mathcal{D}$ consisting of the data -$\mathbf{X}_\mathcal{D}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. - -Let us assume that the true data is generated from a noisy model - -!bt -\[ -\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} -\] -!et - -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. - -In our derivation of the ordinary least squares method we defined then -an approximation to the function $f$ in terms of the parameters -$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, -that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. - -Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function -!bt -\[ -C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. -\] -!et - -We can rewrite this as -!bt -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. -\] -!et - -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error $\bm{\epsilon}$. - -To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. -We use a more compact notation in terms of the expectation value -!bt -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], -\] -!et -and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get -!bt -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], -\] -!et -which, using the abovementioned expectation values can be rewritten as -!bt -\[ -\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, -\] -!et -that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. - - -!split -===== A way to Read the Bias-Variance Tradeoff ===== - -FIGURE: [figures/BiasVariance.png, width=600 frac=0.9] - - -!split -===== Example code for Bias-Variance tradeoff ===== -!bc pycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 - -# Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) - -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -!ec - - -!split -===== Understanding what happens ===== -!bc pycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.preprocessing import PolynomialFeatures -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample - -np.random.seed(2018) - -n = 40 -n_boostraps = 100 -maxdegree = 14 - - -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - - -!ec - -!split -===== Summing up ===== - - - - -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - - - -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below $Var(\epsilon)$, the irreducible error. - - -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - - -You may also find this recent "article":"https://www.pnas.org/content/116/32/15849" of interest. - -!split -===== Another Example from Scikit-Learn's Repository ===== - -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 and 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. - -!bc pycod - - -#print(__doc__) - -import numpy as np -import matplotlib.pyplot as plt -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import cross_val_score - - -def true_fun(X): - return np.cos(1.5 * np.pi * X) - -np.random.seed(0) - -n_samples = 30 -degrees = [1, 4, 15] - -X = np.sort(np.random.rand(n_samples)) -y = true_fun(X) + np.random.randn(n_samples) * 0.1 - -plt.figure(figsize=(14, 5)) -for i in range(len(degrees)): - ax = plt.subplot(1, len(degrees), i + 1) - plt.setp(ax, xticks=(), yticks=()) - - polynomial_features = PolynomialFeatures(degree=degrees[i], - include_bias=False) - linear_regression = LinearRegression() - pipeline = Pipeline([("polynomial_features", polynomial_features), - ("linear_regression", linear_regression)]) - pipeline.fit(X[:, np.newaxis], y) - - # Evaluate the models using crossvalidation - scores = cross_val_score(pipeline, X[:, np.newaxis], y, - scoring="neg_mean_squared_error", cv=10) - - X_test = np.linspace(0, 1, 100) - plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") - plt.plot(X_test, true_fun(X_test), label="True function") - plt.scatter(X, y, edgecolor='b', s=20, label="Samples") - plt.xlabel("x") - plt.ylabel("y") - plt.xlim((0, 1)) - plt.ylim((-2, 2)) - plt.legend(loc="best") - plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( - degrees[i], -scores.mean(), scores.std())) -plt.show() -!ec - - - - -!split -===== Various steps in cross-validation ===== - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - - -!split -===== Cross-validation in brief ===== - -For the various values of $k$ - -o shuffle the dataset randomly. -o Split the dataset into $k$ groups. -o For each unique group: - o Decide which group to use as set for test data - o Take the remaining groups as a training data set - o Fit a model on the training set and evaluate it on the test set - o Retain the evaluation score and discard the model -o Summarize the model using the sample of model evaluation scores - - - -!split -===== Code Example for Cross-validation and $k$-fold Cross-validation ===== - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -!ec - - - -!split -===== More examples on bootstrap and cross-validation and errors ===== - -!bc pycod -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.model_selection import train_test_split -from sklearn.utils import resample -from sklearn.metrics import mean_squared_error -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops - -Maxpolydegree = 30 -X = np.zeros((len(Density),Maxpolydegree)) -X[:,0] = 1.0 -testerror = np.zeros(Maxpolydegree) -trainingerror = np.zeros(Maxpolydegree) -polynomial = np.zeros(Maxpolydegree) - -trials = 100 -for polydegree in range(1, Maxpolydegree): - polynomial[polydegree] = polydegree - for degree in range(polydegree): - X[:,degree] = Density**(degree/3.0) - -# loop over trials in order to estimate the expectation value of the MSE - testerror[polydegree] = 0.0 - trainingerror[polydegree] = 0.0 - for samples in range(trials): - x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) - model = LinearRegression(fit_intercept=False).fit(x_train, y_train) - ypred = model.predict(x_train) - ytilde = model.predict(x_test) - testerror[polydegree] += mean_squared_error(y_test, ytilde) - trainingerror[polydegree] += mean_squared_error(y_train, ypred) - - testerror[polydegree] /= trials - trainingerror[polydegree] /= trials - print("Degree of polynomial: %3d"% polynomial[polydegree]) - print("Mean squared error on training data: %.8f" % trainingerror[polydegree]) - print("Mean squared error on test data: %.8f" % testerror[polydegree]) - -plt.plot(polynomial, np.log10(trainingerror), label='Training Error') -plt.plot(polynomial, np.log10(testerror), label='Test Error') -plt.xlabel('Polynomial degree') -plt.ylabel('log10[MSE]') -plt.legend() -plt.show() - -!ec - -Note that we kept the intercept column in the fitting here. This means that we need to set the _intercept_ in the call to the _Scikit-Learn_ function as _False_. Alternatively, we could have set up the design matrix $X$ without the first column of ones. - -!split -===== The same example but now with cross-validation ===== - -In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error. -!bc pycod -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression, Ridge, Lasso -from sklearn.metrics import mean_squared_error -from sklearn.model_selection import KFold -from sklearn.model_selection import cross_val_score - - -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops - -Maxpolydegree = 30 -X = np.zeros((len(Density),Maxpolydegree)) -X[:,0] = 1.0 -estimated_mse_sklearn = np.zeros(Maxpolydegree) -polynomial = np.zeros(Maxpolydegree) -k =5 -kfold = KFold(n_splits = k) - -for polydegree in range(1, Maxpolydegree): - polynomial[polydegree] = polydegree - for degree in range(polydegree): - X[:,degree] = Density**(degree/3.0) - OLS = LinearRegression(fit_intercept=False) -# loop over trials in order to estimate the expectation value of the MSE - estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold) -#[:, np.newaxis] - estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds) - -plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error') -plt.xlabel('Polynomial degree') -plt.ylabel('log10[MSE]') -plt.legend() -plt.show() - -!ec - - - - - -!split -===== Material for the lab sessions ===== - - -!split -===== Linking the regression analysis with a statistical interpretation ===== - -We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -$\beta$. - - -The -advantage of doing linear regression is that we actually end up with -analytical expressions for several statistical quantities. -Standard least squares and Ridge regression allow us to -derive quantities like the variance and other expectation values in a -rather straightforward way. - - -It is assumed that $\varepsilon_i -\sim \mathcal{N}(0, \sigma^2)$ and the $\varepsilon_{i}$ are -independent, i.e.: -!bt -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} -!et -The randomness of $\varepsilon_i$ implies that -$\mathbf{y}_i$ is also a random variable. In particular, -$\mathbf{y}_i$ is normally distributed, because $\varepsilon_i \sim -\mathcal{N}(0, \sigma^2)$ and $\mathbf{X}_{i,\ast} \, \bm{\beta}$ is a -non-random scalar. To specify the parameters of the distribution of -$\mathbf{y}_i$ we need to calculate its first two moments. - -Recall that $\bm{X}$ is a matrix of dimensionality $n\times p$. The -notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the -row number $i$ and perform a sum over all values $p$. - - -!split -===== Assumptions made ===== - -The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) -that there exists a function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$ -which describe our data -!bt -\[ -\bm{y} = f(\bm{x})+\bm{\varepsilon} -\] -!et - -We approximate this function with our model from the solution of the linear regression equations, that is our -function $f$ is approximated by $\bm{\tilde{y}}$ where we want to minimize $(\bm{y}-\bm{\tilde{y}})^2$, our MSE, with -!bt -\[ -\bm{\tilde{y}} = \bm{X}\bm{\beta}. -\] -!et - -!split -===== Expectation value and variance ===== - -We can calculate the expectation value of $\bm{y}$ for a given element $i$ -!bt -\begin{align*} -\mathbb{E}(y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \bm{\beta}) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} -!et -while -its variance is -!bt -\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i -- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - -[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \bm{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \bm{\beta} + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} -!et -Hence, $y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with -mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$ (not be confused with the singular values of the SVD). - -!split -===== Expectation value and variance for $\bm{\beta}$ ===== - -With the OLS expressions for the optimal parameters $\bm{\hat{\beta}}$ we can evaluate the expectation value -!bt -\[ -\mathbb{E}(\bm{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\bm{\beta}=\bm{\beta}. -\] -!et -This means that the estimator of the regression parameters is unbiased. - -We can also calculate the variance - -The variance of the optimal value $\bm{\hat{\beta}}$ is -!bt -\begin{eqnarray*} -\mbox{Var}(\bm{\hat{\beta}}) & = & \mathbb{E} \{ [\bm{\beta} - \mathbb{E}(\bm{\beta})] [\bm{\beta} - \mathbb{E}(\bm{\beta})]^{T} \} -\\ -& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{y} - \bm{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{y} - \bm{\beta}]^{T} \} -\\ -% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{y}]^{T} \} - \bm{\beta} \, \bm{\beta}^{T} -% \\ -% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{y} \, \mathbf{y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \bm{\beta} \, \bm{\beta}^{T} -% \\ -& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{y} \, \mathbf{y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T} -\\ -& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \bm{\beta} \, \bm{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T} -% \\ -% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \bm{\beta} \, \bm{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} -% \\ -% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \bm{\beta} \bm{\beta}^T -\\ -& = & \bm{\beta} \, \bm{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T} -\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, -\end{eqnarray*} -!et - -where we have used that $\mathbb{E} (\mathbf{y} \mathbf{y}^{T}) = -\mathbf{X} \, \bm{\beta} \, \bm{\beta}^{T} \, \mathbf{X}^{T} + -\sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\bm{\beta}) = \sigma^2 -\, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the -variance of the estimate of the $j$-th regression coefficient: -$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. This may be used to -construct a confidence interval for the estimates. - - -In a similar way, we can obtain analytical expressions for say the -expectation values of the parameters $\bm{\beta}$ and their variance -when we employ Ridge regression, allowing us again to define a confidence interval. - -It is rather straightforward to show that -!bt -\[ -\mathbb{E} \big[ \hat{\bm{\beta}}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\bm{\beta}. -\] -!et -We see clearly that -$\mathbb{E} \big[ \hat{\bm{\beta}}^{\mathrm{Ridge}} \big] \not= \hat{\bm{\beta}}^{\mathrm{OLS}}$ for any $\lambda > 0$. - -We can also compute the variance as - -!bt -\[ -\mbox{Var}[\hat{\bm{\beta}}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, -\] -!et -and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\bm{\beta}$ goes to zero. - -With this, we can compute the difference - -!bt -\[ -\mbox{Var}[\hat{\bm{\beta}}^{\mathrm{OLS}}]-\mbox{Var}(\hat{\bm{\beta}}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. -\] -!et -The difference is non-negative definite since each component of the -matrix product is non-negative definite. -This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - -For more discussions of Ridge regression and calculation of averages, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. - - - - -