Files
FYS-STK4155/doc/LectureNotes/_build/html/week38.html
T
Morten Hjorth-Jensen c1a07a1b9f beta--> theta
2025-09-14 20:26:06 +02:00

1828 lines
109 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en" data-content_root="./" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Week 38: Statistical analysis, bias-variance tradeoff and resampling methods &#8212; Applied Data Analysis and Machine Learning</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/bootstrap.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/vendor/fontawesome/6.5.2/css/all.min.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=fa44fd50" />
<link rel="stylesheet" type="text/css" href="_static/styles/sphinx-book-theme.css?v=eba8b062" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css?v=13237357" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.8ecb98da25f57f5357bf6f572d296f466b2cfe2517ffebfabe82451661e28f02.css?v=6644e6bb" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css?v=4fa983c6" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-design.min.css?v=95c83b7e" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b" />
<script src="_static/vendor/fontawesome/6.5.2/js/all.min.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/documentation_options.js?v=9eb32ce0"></script>
<script src="_static/doctools.js?v=9a2dae69"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/clipboard.min.js?v=a7894cd8"></script>
<script src="_static/copybutton.js?v=f281be69"></script>
<script src="_static/scripts/sphinx-book-theme.js?v=887ef09a"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="_static/togglebutton.js?v=4a39c7ea"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script src="_static/design-tabs.js?v=f930bc37"></script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script async="async" src="_static/sphinx-thebe.js?v=c100c467"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'week38';</script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Exercises week 39" href="exercisesweek39.html" />
<link rel="prev" title="Exercises week 38" href="exercisesweek38.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<div id="pst-skip-link" class="skip-link d-print-none"><a href="#main-content">Skip to main content</a></div>
<div id="pst-scroll-pixel-helper"></div>
<button type="button" class="btn rounded-pill" id="pst-back-to-top">
<i class="fa-solid fa-arrow-up"></i>Back to top</button>
<input type="checkbox"
class="sidebar-toggle"
id="pst-primary-sidebar-checkbox"/>
<label class="overlay overlay-primary" for="pst-primary-sidebar-checkbox"></label>
<input type="checkbox"
class="sidebar-toggle"
id="pst-secondary-sidebar-checkbox"/>
<label class="overlay overlay-secondary" for="pst-secondary-sidebar-checkbox"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search this book..."
aria-label="Search this book..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<div class="pst-async-banner-revealer d-none">
<aside id="bd-header-version-warning" class="d-none d-print-none" aria-label="Version warning"></aside>
</div>
<header class="bd-header navbar navbar-expand-lg bd-navbar d-print-none">
</header>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="intro.html">
<img src="_static/logo.png" class="logo__image only-light" alt="Applied Data Analysis and Machine Learning - Home"/>
<script>document.write(`<img src="_static/logo.png" class="logo__image only-dark" alt="Applied Data Analysis and Machine Learning - Home"/>`);</script>
</a></div>
<div class="sidebar-primary-item">
<script>
document.write(`
<button class="btn search-button-field search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
<span class="search-button__default-text">Search</span>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd class="kbd-shortcut__modifier">K</kbd></span>
</button>
`);
</script></div>
<div class="sidebar-primary-item"><nav class="bd-links bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">About the course</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="schedule.html">Course setting</a></li>
<li class="toctree-l1"><a class="reference internal" href="teachers.html">Teachers and Grading</a></li>
<li class="toctree-l1"><a class="reference internal" href="textbooks.html">Textbooks</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Review of Statistics with Resampling Techniques and Linear Algebra</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="statistics.html">1. Elements of Probability Theory and Statistical Data Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="linalg.html">2. Linear Algebra, Handling of Arrays and more Python Features</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">From Regression to Support Vector Machines</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter1.html">3. Linear Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter2.html">4. Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter3.html">5. Resampling Methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter4.html">6. Logistic Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapteroptimization.html">7. Optimization, the central part of any Machine Learning algortithm</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter5.html">8. Support Vector Machines, overarching aims</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Decision Trees, Ensemble Methods and Boosting</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter6.html">9. Decision trees, overarching aims</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter7.html">10. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Dimensionality Reduction</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter8.html">11. Basic ideas of the Principal Component Analysis (PCA)</a></li>
<li class="toctree-l1"><a class="reference internal" href="clustering.html">12. Clustering and Unsupervised Learning</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Deep Learning Methods</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter9.html">13. Neural networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter10.html">14. Building a Feed Forward Neural Network</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter11.html">15. Solving Differential Equations with Deep Learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter12.html">16. Convolutional Neural Networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter13.html">17. Recurrent neural networks: Overarching view</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Weekly material, notes and exercises</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="exercisesweek34.html">Exercises week 34</a></li>
<li class="toctree-l1"><a class="reference internal" href="week34.html">Week 34: Introduction to the course, Logistics and Practicalities</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek35.html">Exercises week 35</a></li>
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 37</a></li>
<li class="toctree-l1"><a class="reference internal" href="week37.html">Week 37: Gradient descent methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek38.html">Exercises week 38</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Week 38: Statistical analysis, bias-variance tradeoff and resampling methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek39.html">Exercises week 39</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Projects</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="project1.html">Project 1 on Machine Learning, deadline October 6 (midnight), 2025</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main" role="main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article d-print-none">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><button class="sidebar-toggle primary-toggle btn btn-sm" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</button></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<div class="dropdown dropdown-download-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<ul class="dropdown-menu">
<li><a href="_sources/week38.ipynb" target="_blank"
class="btn btn-sm btn-download-source-button dropdown-item"
title="Download source file"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="btn__text-container">.ipynb</span>
</a>
</li>
<li>
<button onclick="window.print()"
class="btn btn-sm btn-download-pdf-button dropdown-item"
title="Print to PDF"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="btn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button" title="light/dark" aria-label="light/dark" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto"></i>
</button>
`);
</script>
<script>
document.write(`
<button class="btn btn-sm pst-navbar-icon search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass fa-lg"></i>
</button>
`);
</script>
<button class="sidebar-toggle secondary-toggle btn btn-sm" title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</button>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Week 38: Statistical analysis, bias-variance tradeoff and resampling methods</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#plans-for-week-38-lecture-monday-september-15">Plans for week 38, lecture Monday September 15</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#readings-and-videos">Readings and Videos</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#linking-the-regression-analysis-with-a-statistical-interpretation">Linking the regression analysis with a statistical interpretation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#assumptions-made">Assumptions made</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#expectation-value-and-variance">Expectation value and variance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#expectation-value-and-variance-for-boldsymbol-theta">Expectation value and variance for <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#deriving-ols-from-a-probability-distribution">Deriving OLS from a probability distribution</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#independent-and-identically-distributed-iid">Independent and Identically Distributed (iid)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#maximum-likelihood-estimation-mle">Maximum Likelihood Estimation (MLE)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-new-cost-function">A new Cost Function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#why-resampling-methods">Why resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods">Resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-approaches-can-be-computationally-expensive">Resampling approaches can be computationally expensive</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">Why resampling methods ?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#statistical-analysis">Statistical analysis</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">Resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap">Resampling methods: Bootstrap</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-central-limit-theorem">The Central Limit Theorem</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#finding-the-limit">Finding the Limit</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#rewriting-the-delta-function">Rewriting the <span class="math notranslate nohighlight">\(\delta\)</span>-function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#identifying-terms">Identifying Terms</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#wrapping-it-up">Wrapping it up</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#confidence-intervals">Confidence Intervals</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#standard-approach-based-on-the-normal-distribution">Standard Approach based on the Normal Distribution</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-background">Resampling methods: Bootstrap background</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-more-bootstrap-background">Resampling methods: More Bootstrap background</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-approach">Resampling methods: Bootstrap approach</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-steps">Resampling methods: Bootstrap steps</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example-for-the-bootstrap-method">Code example for the Bootstrap method</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#plotting-the-histogram">Plotting the Histogram</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-bias-variance-tradeoff">The bias-variance tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-way-to-read-the-bias-variance-tradeoff">A way to Read the Bias-Variance Tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#example-code-for-bias-variance-tradeoff">Example code for Bias-Variance tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#understanding-what-happens">Understanding what happens</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#summing-up">Summing up</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#another-example-from-scikit-learn-s-repository">Another Example from Scikit-Learns Repository</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#various-steps-in-cross-validation">Various steps in cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#cross-validation-in-brief">Cross-validation in brief</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example-for-cross-validation-and-k-fold-cross-validation">Code Example for Cross-validation and <span class="math notranslate nohighlight">\(k\)</span>-fold Cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-examples-on-bootstrap-and-cross-validation-and-errors">More examples on bootstrap and cross-validation and errors</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-same-example-but-now-with-cross-validation">The same example but now with cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#material-for-the-lab-sessions">Material for the lab sessions</a></li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html week38.do.txt --no_mako -->
<!-- dom:TITLE: Week 38: Statistical analysis, bias-variance tradeoff and resampling methods --><section class="tex2jax_ignore mathjax_ignore" id="week-38-statistical-analysis-bias-variance-tradeoff-and-resampling-methods">
<h1>Week 38: Statistical analysis, bias-variance tradeoff and resampling methods<a class="headerlink" href="#week-38-statistical-analysis-bias-variance-tradeoff-and-resampling-methods" title="Link to this heading">#</a></h1>
<p><strong>Morten Hjorth-Jensen</strong>, Department of Physics and Center for Computing in Science Education, University of Oslo, Norway</p>
<p>Date: <strong>September 15-19, 2025</strong></p>
<section id="plans-for-week-38-lecture-monday-september-15">
<h2>Plans for week 38, lecture Monday September 15<a class="headerlink" href="#plans-for-week-38-lecture-monday-september-15" title="Link to this heading">#</a></h2>
<p><strong>Material for the lecture on Monday September 15.</strong></p>
<ol class="arabic simple">
<li><p>Statistical interpretation of OLS and various expectation values</p></li>
<li><p>Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff</p></li>
<li><p>The material we did not cover last week, that is on more advanced methods for updating the learning rate, are covered by its own video. We will briefly discuss these topics at the beginning of the lecture and during the lab sessions. See video on ADAgrad, RMSprop and ADAM (material from last week not covered during lecture) at <a class="reference external" href="https://youtu.be/J_41Hld6tTU">https://youtu.be/J_41Hld6tTU</a></p></li>
</ol>
<!-- * [Video of Lecture](https://youtu.be/omLmp_kkie0) -->
<!-- * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember9.pdf) --></section>
<section id="readings-and-videos">
<h2>Readings and Videos<a class="headerlink" href="#readings-and-videos" title="Link to this heading">#</a></h2>
<ol class="arabic simple">
<li><p>Raschka et al, pages 175-192</p></li>
<li><p>Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). See <a class="reference external" href="https://link.springer.com/book/10.1007/978-0-387-84858-7">https://link.springer.com/book/10.1007/978-0-387-84858-7</a>.</p></li>
<li><p><a class="reference external" href="https://www.youtube.com/watch?v=EuBBz3bI-aA">Video on bias-variance tradeoff</a></p></li>
<li><p><a class="reference external" href="https://www.youtube.com/watch?v=Xz0x-8-cgaQ">Video on Bootstrapping</a></p></li>
<li><p><a class="reference external" href="https://www.youtube.com/watch?v=fSytzGwwBVw">Video on cross validation</a></p></li>
</ol>
<p>For the lab session, the following video on cross validation (from 2024), could be helpful, see <a class="reference external" href="https://www.youtube.com/watch?v=T9jjWsmsd1o">https://www.youtube.com/watch?v=T9jjWsmsd1o</a></p>
</section>
<section id="linking-the-regression-analysis-with-a-statistical-interpretation">
<h2>Linking the regression analysis with a statistical interpretation<a class="headerlink" href="#linking-the-regression-analysis-with-a-statistical-interpretation" title="Link to this heading">#</a></h2>
<p>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
<span class="math notranslate nohighlight">\(\theta\)</span>.</p>
<p>On of the advantages of doing linear regression is that we actually end up with
analytical expressions for several statistical quantities.<br />
Standard least squares and Ridge regression allow us to
derive quantities like the variance and other expectation values in a
rather straightforward way.</p>
<p>It is assumed that <span class="math notranslate nohighlight">\(\varepsilon_i
\sim \mathcal{N}(0, \sigma^2)\)</span> and the <span class="math notranslate nohighlight">\(\varepsilon_{i}\)</span> are
independent, i.e.:</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*}
\mbox{Cov}(\varepsilon_{i_1},
\varepsilon_{i_2}) &amp; = \left\{ \begin{array}{lcc} \sigma^2 &amp; \mbox{if}
&amp; i_1 = i_2, \\ 0 &amp; \mbox{if} &amp; i_1 \not= i_2. \end{array} \right.
\end{align*}
\end{split}\]</div>
<p>The randomness of <span class="math notranslate nohighlight">\(\varepsilon_i\)</span> implies that
<span class="math notranslate nohighlight">\(\mathbf{y}_i\)</span> is also a random variable. In particular,
<span class="math notranslate nohighlight">\(\mathbf{y}_i\)</span> is normally distributed, because <span class="math notranslate nohighlight">\(\varepsilon_i \sim
\mathcal{N}(0, \sigma^2)\)</span> and <span class="math notranslate nohighlight">\(\mathbf{X}_{i,\ast} \, \boldsymbol{\theta}\)</span> is a
non-random scalar. To specify the parameters of the distribution of
<span class="math notranslate nohighlight">\(\mathbf{y}_i\)</span> we need to calculate its first two moments.</p>
<p>Recall that <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span> is a matrix of dimensionality <span class="math notranslate nohighlight">\(n\times p\)</span>. The
notation above <span class="math notranslate nohighlight">\(\mathbf{X}_{i,\ast}\)</span> means that we are looking at the
row number <span class="math notranslate nohighlight">\(i\)</span> and perform a sum over all values <span class="math notranslate nohighlight">\(p\)</span>.</p>
</section>
<section id="assumptions-made">
<h2>Assumptions made<a class="headerlink" href="#assumptions-made" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(f(\boldsymbol{x})\)</span> and a normal distributed error <span class="math notranslate nohighlight">\(\boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2)\)</span>
which describe our data</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
\]</div>
<p>We approximate this function with our model from the solution of the linear regression equations, that is our
function <span class="math notranslate nohighlight">\(f\)</span> is approximated by <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}\)</span> where we want to minimize <span class="math notranslate nohighlight">\((\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\)</span>, our MSE, with</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\theta}.
\]</div>
</section>
<section id="expectation-value-and-variance">
<h2>Expectation value and variance<a class="headerlink" href="#expectation-value-and-variance" title="Link to this heading">#</a></h2>
<p>We can calculate the expectation value of <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> for a given element <span class="math notranslate nohighlight">\(i\)</span></p>
<div class="math notranslate nohighlight">
\[
\begin{align*}
\mathbb{E}(y_i) &amp; =
\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\theta}) + \mathbb{E}(\varepsilon_i)
\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \theta,
\end{align*}
\]</div>
<p>while
its variance is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*} \mbox{Var}(y_i) &amp; = \mathbb{E} \{ [y_i
- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
[\mathbb{E}(y_i)]^2 \\ &amp; = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
\theta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\theta})^2 \\ &amp;
= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\theta})^2 + 2 \varepsilon_i
\mathbf{X}_{i, \ast} \, \boldsymbol{\theta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
\ast} \, \theta)^2 \\ &amp; = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\theta})^2 + 2
\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\theta} +
\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\theta})^2
\\ &amp; = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
\end{split}\]</div>
<p>Hence, <span class="math notranslate nohighlight">\(y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\theta}, \sigma^2)\)</span>, that is <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> follows a normal distribution with
mean value <span class="math notranslate nohighlight">\(\boldsymbol{X}\boldsymbol{\theta}\)</span> and variance <span class="math notranslate nohighlight">\(\sigma^2\)</span> (not be confused with the singular values of the SVD).</p>
</section>
<section id="expectation-value-and-variance-for-boldsymbol-theta">
<h2>Expectation value and variance for <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span><a class="headerlink" href="#expectation-value-and-variance-for-boldsymbol-theta" title="Link to this heading">#</a></h2>
<p>With the OLS expressions for the optimal parameters <span class="math notranslate nohighlight">\(\boldsymbol{\hat{\theta}}\)</span> we can evaluate the expectation value</p>
<div class="math notranslate nohighlight">
\[
\mathbb{E}(\boldsymbol{\hat{\theta}}) = \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{\theta}=\boldsymbol{\theta}.
\]</div>
<p>This means that the estimator of the regression parameters is unbiased.</p>
<p>We can also calculate the variance</p>
<p>The variance of the optimal value <span class="math notranslate nohighlight">\(\boldsymbol{\hat{\theta}}\)</span> is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{eqnarray*}
\mbox{Var}(\boldsymbol{\hat{\theta}}) &amp; = &amp; \mathbb{E} \{ [\boldsymbol{\theta} - \mathbb{E}(\boldsymbol{\theta})] [\boldsymbol{\theta} - \mathbb{E}(\boldsymbol{\theta})]^{T} \}
\\
&amp; = &amp; \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\theta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\theta}]^{T} \}
\\
% &amp; = &amp; \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{\theta} \, \boldsymbol{\theta}^{T}
% \\
% &amp; = &amp; \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{\theta} \, \boldsymbol{\theta}^{T}
% \\
&amp; = &amp; (\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{\theta} \, \boldsymbol{\theta}^{T}
\\
&amp; = &amp; (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\theta} \, \boldsymbol{\theta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\theta} \, \boldsymbol{\theta}^{T}
% \\
% &amp; = &amp; (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\theta} \, \boldsymbol{\theta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
% \\
% &amp; &amp; + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\theta} \boldsymbol{\theta}^T
\\
&amp; = &amp; \boldsymbol{\theta} \, \boldsymbol{\theta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\theta} \, \boldsymbol{\theta}^{T}
\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
\end{eqnarray*}
\end{split}\]</div>
<p>where we have used that <span class="math notranslate nohighlight">\(\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
\mathbf{X} \, \boldsymbol{\theta} \, \boldsymbol{\theta}^{T} \, \mathbf{X}^{T} +
\sigma^2 \, \mathbf{I}_{nn}\)</span>. From <span class="math notranslate nohighlight">\(\mbox{Var}(\boldsymbol{\theta}) = \sigma^2
\, (\mathbf{X}^{T} \mathbf{X})^{-1}\)</span>, one obtains an estimate of the
variance of the estimate of the <span class="math notranslate nohighlight">\(j\)</span>-th regression coefficient:
<span class="math notranslate nohighlight">\(\boldsymbol{\sigma}^2 (\boldsymbol{\theta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \)</span>. This may be used to
construct a confidence interval for the estimates.</p>
<p>In a similar way, we can obtain analytical expressions for say the
expectation values of the parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> and their variance
when we employ Ridge regression, allowing us again to define a confidence interval.</p>
<p>It is rather straightforward to show that</p>
<div class="math notranslate nohighlight">
\[
\mathbb{E} \big[ \boldsymbol{\theta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\theta}^{\mathrm{OLS}}.
\]</div>
<p>We see clearly that
<span class="math notranslate nohighlight">\(\mathbb{E} \big[ \boldsymbol{\theta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\theta}^{\mathrm{OLS}}\)</span> for any <span class="math notranslate nohighlight">\(\lambda &gt; 0\)</span>. We say then that the ridge estimator is biased.</p>
<p>We can also compute the variance as</p>
<div class="math notranslate nohighlight">
\[
\mbox{Var}[\boldsymbol{\theta}^{\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},
\]</div>
<p>and it is easy to see that if the parameter <span class="math notranslate nohighlight">\(\lambda\)</span> goes to infinity then the variance of Ridge parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> goes to zero.</p>
<p>With this, we can compute the difference</p>
<div class="math notranslate nohighlight">
\[
\mbox{Var}[\boldsymbol{\theta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\theta}^{\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}.
\]</div>
<p>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 <span class="math notranslate nohighlight">\(\lambda &gt; 0\)</span> be larger than the variance of <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.</p>
</section>
<section id="deriving-ols-from-a-probability-distribution">
<h2>Deriving OLS from a probability distribution<a class="headerlink" href="#deriving-ols-from-a-probability-distribution" title="Link to this heading">#</a></h2>
<p>Our basic assumption when we derived the OLS equations was to assume
that our output is determined by a given continuous function
<span class="math notranslate nohighlight">\(f(\boldsymbol{x})\)</span> and a random noise <span class="math notranslate nohighlight">\(\boldsymbol{\epsilon}\)</span> given by the normal
distribution with zero mean value and an undetermined variance
<span class="math notranslate nohighlight">\(\sigma^2\)</span>.</p>
<p>We found above that the outputs <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> have a mean value given by
<span class="math notranslate nohighlight">\(\boldsymbol{X}\hat{\boldsymbol{\theta}}\)</span> and variance <span class="math notranslate nohighlight">\(\sigma^2\)</span>. 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 <span class="math notranslate nohighlight">\(\boldsymbol{X}\hat{\boldsymbol{\theta}}\)</span>. This means that a
single output <span class="math notranslate nohighlight">\(y_i\)</span> is given by the Gaussian distribution</p>
<div class="math notranslate nohighlight">
\[
y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\theta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\theta})^2}{2\sigma^2}\right]}.
\]</div>
</section>
<section id="independent-and-identically-distributed-iid">
<h2>Independent and Identically Distributed (iid)<a class="headerlink" href="#independent-and-identically-distributed-iid" title="Link to this heading">#</a></h2>
<p>We assume now that the various <span class="math notranslate nohighlight">\(y_i\)</span> values are stochastically distributed according to the above Gaussian distribution.
We define this distribution as</p>
<div class="math notranslate nohighlight">
\[
p(y_i, \boldsymbol{X}\vert\boldsymbol{\theta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\theta})^2}{2\sigma^2}\right]},
\]</div>
<p>which reads as finding the likelihood of an event <span class="math notranslate nohighlight">\(y_i\)</span> with the input variables <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span> given the parameters (to be determined) <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span>.</p>
<p>Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> as the product of the single events, that is we have</p>
<div class="math notranslate nohighlight">
\[
p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\theta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\theta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\theta}).
\]</div>
<p>We will write this in a more compact form reserving <span class="math notranslate nohighlight">\(\boldsymbol{D}\)</span> 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</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
\]</div>
<p>In the more general case the various inputs should be replaced by the possible features represented by the input data set <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span>.
We can now rewrite the above probability as</p>
<div class="math notranslate nohighlight">
\[
p(\boldsymbol{D}\vert\boldsymbol{\theta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\theta})^2}{2\sigma^2}\right]}.
\]</div>
<p>It is a conditional probability (see below) and reads as the likelihood of a domain of events <span class="math notranslate nohighlight">\(\boldsymbol{D}\)</span> given a set of parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span>.</p>
</section>
<section id="maximum-likelihood-estimation-mle">
<h2>Maximum Likelihood Estimation (MLE)<a class="headerlink" href="#maximum-likelihood-estimation-mle" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>We will assume here that our events are given by the above Gaussian
distribution and we will determine the optimal parameters <span class="math notranslate nohighlight">\(\theta\)</span> 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.</p>
<p>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.</p>
<p>Note also that maximization/minimization of the logarithm of the PDF
is equivalent to the maximization/minimization of the function itself.</p>
</section>
<section id="a-new-cost-function">
<h2>A new Cost Function<a class="headerlink" href="#a-new-cost-function" title="Link to this heading">#</a></h2>
<p>We could now define a new cost function to minimize, namely the negative logarithm of the above PDF</p>
<div class="math notranslate nohighlight">
\[
C(\boldsymbol{\theta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\theta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\theta})},
\]</div>
<p>which becomes</p>
<div class="math notranslate nohighlight">
\[
C(\boldsymbol{\theta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta})\vert\vert_2^2}{2\sigma^2}.
\]</div>
<p>Taking the derivative of the <em>new</em> cost function with respect to the parameters <span class="math notranslate nohighlight">\(\theta\)</span> we recognize our familiar OLS equation, namely</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right) =0,
\]</div>
<p>which leads to the well-known OLS equation for the optimal paramters <span class="math notranslate nohighlight">\(\theta\)</span></p>
<div class="math notranslate nohighlight">
\[
\hat{\boldsymbol{\theta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
\]</div>
<p>Next week we will make a similar analysis for Ridge and Lasso regression</p>
</section>
<section id="why-resampling-methods">
<h2>Why resampling methods<a class="headerlink" href="#why-resampling-methods" title="Link to this heading">#</a></h2>
<p>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</p>
<ol class="arabic simple">
<li><p>look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff</p></li>
<li><p>introduce resampling techniques like cross-validation, bootstrapping and jackknife and more</p></li>
</ol>
<p>and discuss how to select a given model (one of the difficult parts in machine learning).</p>
</section>
<section id="resampling-methods">
<h2>Resampling methods<a class="headerlink" href="#resampling-methods" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>Two resampling methods are often used in Machine Learning analyses,</p>
<ol class="arabic simple">
<li><p>The <strong>bootstrap method</strong></p></li>
<li><p>and <strong>Cross-Validation</strong></p></li>
</ol>
<p>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.</p>
</section>
<section id="resampling-approaches-can-be-computationally-expensive">
<h2>Resampling approaches can be computationally expensive<a class="headerlink" href="#resampling-approaches-can-be-computationally-expensive" title="Link to this heading">#</a></h2>
<p>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 models 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.</p>
</section>
<section id="id1">
<h2>Why resampling methods ?<a class="headerlink" href="#id1" title="Link to this heading">#</a></h2>
<p><strong>Statistical analysis.</strong></p>
<ul class="simple">
<li><p>Our simulations can be treated as <em>computer experiments</em>. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.</p></li>
<li><p>The results can be analysed with the same statistical tools as we would use when analysing experimental data.</p></li>
<li><p>As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.</p></li>
</ul>
</section>
<section id="statistical-analysis">
<h2>Statistical analysis<a class="headerlink" href="#statistical-analysis" title="Link to this heading">#</a></h2>
<ul class="simple">
<li><p>As in other experiments, many numerical experiments have two classes of errors:</p>
<ul>
<li><p>Statistical errors</p></li>
<li><p>Systematical errors</p></li>
</ul>
</li>
<li><p>Statistical errors can be estimated using standard tools from statistics</p></li>
<li><p>Systematical errors are method specific and must be treated differently from case to case.</p></li>
</ul>
</section>
<section id="id2">
<h2>Resampling methods<a class="headerlink" href="#id2" title="Link to this heading">#</a></h2>
<p>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.</p>
<p>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.</p>
<p>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</p>
<ol class="arabic simple">
<li><p>prediction error or simply the <strong>test error</strong> <span class="math notranslate nohighlight">\(\mathrm{Err_{Test}}\)</span>, 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</p></li>
<li><p>training error <span class="math notranslate nohighlight">\(\mathrm{Err_{Train}}\)</span>, which is the average loss over the training data.</p></li>
</ol>
<p>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.</p>
</section>
<section id="resampling-methods-bootstrap">
<h2>Resampling methods: Bootstrap<a class="headerlink" href="#resampling-methods-bootstrap" title="Link to this heading">#</a></h2>
<p>Bootstrapping is a <a class="reference external" href="https://en.wikipedia.org/wiki/Nonparametric_statistics">non-parametric approach</a> to statistical inference
that substitutes computation for more traditional distributional
assumptions and asymptotic results. Bootstrapping offers a number of
advantages:</p>
<ol class="arabic simple">
<li><p>The bootstrap is quite general, although there are some cases in which it fails.</p></li>
<li><p>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.</p></li>
<li><p>It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.</p></li>
<li><p>It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).</p></li>
</ol>
<p>The textbook by <a class="reference external" href="https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A">Davison on the Bootstrap Methods and their Applications</a> 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 <a class="reference external" href="https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317">Efron and Tibshirani</a>.</p>
<p>Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called <strong>central limit theorem</strong>.</p>
</section>
<section id="the-central-limit-theorem">
<h2>The Central Limit Theorem<a class="headerlink" href="#the-central-limit-theorem" title="Link to this heading">#</a></h2>
<p>Suppose we have a PDF <span class="math notranslate nohighlight">\(p(x)\)</span> from which we generate a series <span class="math notranslate nohighlight">\(N\)</span>
of averages <span class="math notranslate nohighlight">\(\mathbb{E}[x_i]\)</span>. Each mean value <span class="math notranslate nohighlight">\(\mathbb{E}[x_i]\)</span>
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 <span class="math notranslate nohighlight">\(\mathbb{E}[x_i]=x_i\)</span> in the discussion
which follows. We do the same for <span class="math notranslate nohighlight">\(\mathbb{E}[z]=z\)</span>.</p>
<p>If we compute the mean <span class="math notranslate nohighlight">\(z\)</span> of <span class="math notranslate nohighlight">\(m\)</span> such mean values <span class="math notranslate nohighlight">\(x_i\)</span></p>
<div class="math notranslate nohighlight">
\[
z=\frac{x_1+x_2+\dots+x_m}{m},
\]</div>
<p>the question we pose is which is the PDF of the new variable <span class="math notranslate nohighlight">\(z\)</span>.</p>
</section>
<section id="finding-the-limit">
<h2>Finding the Limit<a class="headerlink" href="#finding-the-limit" title="Link to this heading">#</a></h2>
<p>The probability of obtaining an average value <span class="math notranslate nohighlight">\(z\)</span> is the product of the
probabilities of obtaining arbitrary individual mean values <span class="math notranslate nohighlight">\(x_i\)</span>,
but with the constraint that the average is <span class="math notranslate nohighlight">\(z\)</span>. We can express this through
the following expression</p>
<div class="math notranslate nohighlight">
\[
\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}),
\]</div>
<p>where the <span class="math notranslate nohighlight">\(\delta\)</span>-function enbodies the constraint that the mean is <span class="math notranslate nohighlight">\(z\)</span>.
All measurements that lead to each individual <span class="math notranslate nohighlight">\(x_i\)</span> are expected to
be independent, which in turn means that we can express <span class="math notranslate nohighlight">\(\tilde{p}\)</span> as the
product of individual <span class="math notranslate nohighlight">\(p(x_i)\)</span>. The independence assumption is important in the derivation of the central limit theorem.</p>
</section>
<section id="rewriting-the-delta-function">
<h2>Rewriting the <span class="math notranslate nohighlight">\(\delta\)</span>-function<a class="headerlink" href="#rewriting-the-delta-function" title="Link to this heading">#</a></h2>
<p>If we use the integral expression for the <span class="math notranslate nohighlight">\(\delta\)</span>-function</p>
<div class="math notranslate nohighlight">
\[
\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)},
\]</div>
<p>and inserting <span class="math notranslate nohighlight">\(e^{i\mu q-i\mu q}\)</span> where <span class="math notranslate nohighlight">\(\mu\)</span> is the mean value
we arrive at</p>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<p>with the integral over <span class="math notranslate nohighlight">\(x\)</span> resulting in</p>
<div class="math notranslate nohighlight">
\[
\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].
\]</div>
</section>
<section id="identifying-terms">
<h2>Identifying Terms<a class="headerlink" href="#identifying-terms" title="Link to this heading">#</a></h2>
<p>The second term on the rhs disappears since this is just the mean and
employing the definition of <span class="math notranslate nohighlight">\(\sigma^2\)</span> we have</p>
<div class="math notranslate nohighlight">
\[
\int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}=
1-\frac{q^2\sigma^2}{2m^2}+\dots,
\]</div>
<p>resulting in</p>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<p>and in the limit <span class="math notranslate nohighlight">\(m\rightarrow \infty\)</span> we obtain</p>
<div class="math notranslate nohighlight">
\[
\tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})}
\exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)},
\]</div>
<p>which is the normal distribution with variance
<span class="math notranslate nohighlight">\(\sigma^2_m=\sigma^2/m\)</span>, where <span class="math notranslate nohighlight">\(\sigma\)</span> is the variance of the PDF <span class="math notranslate nohighlight">\(p(x)\)</span>
and <span class="math notranslate nohighlight">\(\mu\)</span> is also the mean of the PDF <span class="math notranslate nohighlight">\(p(x)\)</span>.</p>
</section>
<section id="wrapping-it-up">
<h2>Wrapping it up<a class="headerlink" href="#wrapping-it-up" title="Link to this heading">#</a></h2>
<p>Thus, the central limit theorem states that the PDF <span class="math notranslate nohighlight">\(\tilde{p}(z)\)</span> of
the average of <span class="math notranslate nohighlight">\(m\)</span> random values corresponding to a PDF <span class="math notranslate nohighlight">\(p(x)\)</span>
is a normal distribution whose mean is the
mean value of the PDF <span class="math notranslate nohighlight">\(p(x)\)</span> and whose variance is the variance
of the PDF <span class="math notranslate nohighlight">\(p(x)\)</span> divided by <span class="math notranslate nohighlight">\(m\)</span>, the number of values used to compute <span class="math notranslate nohighlight">\(z\)</span>.</p>
<p>The central limit theorem leads to the well-known expression for the
standard deviation, given by</p>
<div class="math notranslate nohighlight">
\[
\sigma_m=
\frac{\sigma}{\sqrt{m}}.
\]</div>
<p>The latter is true only if the average value is known exactly. This is obtained in the limit
<span class="math notranslate nohighlight">\(m\rightarrow \infty\)</span> only. Because the mean and the variance are measured quantities we obtain
the familiar expression in statistics (the so-called Bessel correction)</p>
<div class="math notranslate nohighlight">
\[
\sigma_m\approx
\frac{\sigma}{\sqrt{m-1}}.
\]</div>
<p>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 <span class="math notranslate nohighlight">\(x\)</span> 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.</p>
<p>The theorem is satisfied by a large class of PDFs. Note however that for a
finite <span class="math notranslate nohighlight">\(m\)</span>, it is not always possible to find a closed form /analytic expression for
<span class="math notranslate nohighlight">\(\tilde{p}(x)\)</span>.</p>
</section>
<section id="confidence-intervals">
<h2>Confidence Intervals<a class="headerlink" href="#confidence-intervals" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> from linear regression.</p>
<p>With the OLS expressions for the parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> we found
<span class="math notranslate nohighlight">\(\mathbb{E}(\boldsymbol{\theta}) = \boldsymbol{\theta}\)</span>, which means that the estimator of the regression parameters is unbiased.</p>
<p>In the exercises this week we show that the variance of the estimate of the <span class="math notranslate nohighlight">\(j\)</span>-th regression coefficient is
<span class="math notranslate nohighlight">\(\boldsymbol{\sigma}^2 (\boldsymbol{\theta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \)</span>.</p>
<p>This quantity can be used to
construct a confidence interval for the estimates.</p>
</section>
<section id="standard-approach-based-on-the-normal-distribution">
<h2>Standard Approach based on the Normal Distribution<a class="headerlink" href="#standard-approach-based-on-the-normal-distribution" title="Link to this heading">#</a></h2>
<p>We will assume that the parameters <span class="math notranslate nohighlight">\(\theta\)</span> follow a normal
distribution. We can then define the confidence interval. Here we will be using as
shorthands <span class="math notranslate nohighlight">\(\mu_{\theta}\)</span> for the above mean value and <span class="math notranslate nohighlight">\(\sigma_{\theta}\)</span>
for the standard deviation. We have then a confidence interval</p>
<div class="math notranslate nohighlight">
\[
\left(\mu_{\theta}\pm \frac{z\sigma_{\theta}}{\sqrt{n}}\right),
\]</div>
<p>where <span class="math notranslate nohighlight">\(z\)</span> defines the level of certainty (or confidence). For a normal
distribution typical parameters are <span class="math notranslate nohighlight">\(z=2.576\)</span> which corresponds to a
confidence of <span class="math notranslate nohighlight">\(99\%\)</span> while <span class="math notranslate nohighlight">\(z=1.96\)</span> corresponds to a confidence of
<span class="math notranslate nohighlight">\(95\%\)</span>. A confidence level of <span class="math notranslate nohighlight">\(95\%\)</span> is commonly used and it is
normally referred to as a <em>two-sigmas</em> confidence level, that is we
approximate <span class="math notranslate nohighlight">\(z\approx 2\)</span>.</p>
<p>For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by <a class="reference external" href="https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A">Davison on the Bootstrap Methods and their Applications</a></p>
<p>In this text you will also find an in-depth discussion of the
Bootstrap method, why it works and various theorems related to it.</p>
</section>
<section id="resampling-methods-bootstrap-background">
<h2>Resampling methods: Bootstrap background<a class="headerlink" href="#resampling-methods-bootstrap-background" title="Link to this heading">#</a></h2>
<p>Since <span class="math notranslate nohighlight">\(\widehat{\theta} = \widehat{\theta}(\boldsymbol{X})\)</span> is a function of random variables,
<span class="math notranslate nohighlight">\(\widehat{\theta}\)</span> itself must be a random variable. Thus it has
a pdf, call this function <span class="math notranslate nohighlight">\(p(\boldsymbol{t})\)</span>. The aim of the bootstrap is to
estimate <span class="math notranslate nohighlight">\(p(\boldsymbol{t})\)</span> by the relative frequency of
<span class="math notranslate nohighlight">\(\widehat{\theta}\)</span>. You can think of this as using a histogram
in the place of <span class="math notranslate nohighlight">\(p(\boldsymbol{t})\)</span>. If the relative frequency closely
resembles <span class="math notranslate nohighlight">\(p(\vec{t})\)</span>, then using numerics, it is straight forward to
estimate all the interesting parameters of <span class="math notranslate nohighlight">\(p(\boldsymbol{t})\)</span> using point
estimators.</p>
</section>
<section id="resampling-methods-more-bootstrap-background">
<h2>Resampling methods: More Bootstrap background<a class="headerlink" href="#resampling-methods-more-bootstrap-background" title="Link to this heading">#</a></h2>
<p>In the case that <span class="math notranslate nohighlight">\(\widehat{\theta}\)</span> 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 <span class="math notranslate nohighlight">\(X_i\)</span>, <span class="math notranslate nohighlight">\(p(x)\)</span>, had been known, then it would have
been straightforward to do this by:</p>
<ol class="arabic simple">
<li><p>Drawing lots of numbers from <span class="math notranslate nohighlight">\(p(x)\)</span>, suppose we call one such set of numbers <span class="math notranslate nohighlight">\((X_1^*, X_2^*, \cdots, X_n^*)\)</span>.</p></li>
<li><p>Then using these numbers, we could compute a replica of <span class="math notranslate nohighlight">\(\widehat{\theta}\)</span> called <span class="math notranslate nohighlight">\(\widehat{\theta}^*\)</span>.</p></li>
</ol>
<p>By repeated use of the above two points, many
estimates of <span class="math notranslate nohighlight">\(\widehat{\theta}\)</span> can be obtained. The
idea is to use the relative frequency of <span class="math notranslate nohighlight">\(\widehat{\theta}^*\)</span>
(think of a histogram) as an estimate of <span class="math notranslate nohighlight">\(p(\boldsymbol{t})\)</span>.</p>
</section>
<section id="resampling-methods-bootstrap-approach">
<h2>Resampling methods: Bootstrap approach<a class="headerlink" href="#resampling-methods-bootstrap-approach" title="Link to this heading">#</a></h2>
<p>But
unless there is enough information available about the process that
generated <span class="math notranslate nohighlight">\(X_1,X_2,\cdots,X_n\)</span>, <span class="math notranslate nohighlight">\(p(x)\)</span> is in general
unknown. Therefore, <a class="reference external" href="https://projecteuclid.org/euclid.aos/1176344552">Efron in 1979</a> asked the
question: What if we replace <span class="math notranslate nohighlight">\(p(x)\)</span> by the relative frequency
of the observation <span class="math notranslate nohighlight">\(X_i\)</span>?</p>
<p>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.</p>
</section>
<section id="resampling-methods-bootstrap-steps">
<h2>Resampling methods: Bootstrap steps<a class="headerlink" href="#resampling-methods-bootstrap-steps" title="Link to this heading">#</a></h2>
<p>The independent bootstrap works like this:</p>
<ol class="arabic simple">
<li><p>Draw with replacement <span class="math notranslate nohighlight">\(n\)</span> numbers for the observed variables <span class="math notranslate nohighlight">\(\boldsymbol{x} = (x_1,x_2,\cdots,x_n)\)</span>.</p></li>
<li><p>Define a vector <span class="math notranslate nohighlight">\(\boldsymbol{x}^*\)</span> containing the values which were drawn from <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span>.</p></li>
<li><p>Using the vector <span class="math notranslate nohighlight">\(\boldsymbol{x}^*\)</span> compute <span class="math notranslate nohighlight">\(\widehat{\theta}^*\)</span> by evaluating <span class="math notranslate nohighlight">\(\widehat \theta\)</span> under the observations <span class="math notranslate nohighlight">\(\boldsymbol{x}^*\)</span>.</p></li>
<li><p>Repeat this process <span class="math notranslate nohighlight">\(k\)</span> times.</p></li>
</ol>
<p>When you are done, you can draw a histogram of the relative frequency
of <span class="math notranslate nohighlight">\(\widehat \theta^*\)</span>. This is your estimate of the probability
distribution <span class="math notranslate nohighlight">\(p(t)\)</span>. Using this probability distribution you can
estimate any statistics thereof. In principle you never draw the
histogram of the relative frequency of <span class="math notranslate nohighlight">\(\widehat{\theta}^*\)</span>. Instead
you use the estimators corresponding to the statistic of interest. For
example, if you are interested in estimating the variance of <span class="math notranslate nohighlight">\(\widehat
\theta\)</span>, apply the etsimator <span class="math notranslate nohighlight">\(\widehat \sigma^2\)</span> to the values
<span class="math notranslate nohighlight">\(\widehat \theta^*\)</span>.</p>
</section>
<section id="code-example-for-the-bootstrap-method">
<h2>Code example for the Bootstrap method<a class="headerlink" href="#code-example-for-the-bootstrap-method" title="Link to this heading">#</a></h2>
<p>The following code starts with a Gaussian distribution with mean value
<span class="math notranslate nohighlight">\(\mu =100\)</span> and variance <span class="math notranslate nohighlight">\(\sigma=15\)</span>. 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 <span class="math notranslate nohighlight">\(\mu=100\)</span> but with standard deviation
<span class="math notranslate nohighlight">\(\sigma/\sqrt{n}\)</span>, where <span class="math notranslate nohighlight">\(n\)</span> 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.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>%matplotlib inline
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(&quot;Bootstrap Statistics :&quot;)
print(&quot;original bias std. error&quot;)
print(&quot;%8g %8g %14g %15g&quot; % (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)
</pre></div>
</div>
</div>
</div>
<p>We see that our new variance and from that the standard deviation, agrees with the central limit theorem.</p>
</section>
<section id="plotting-the-histogram">
<h2>Plotting the Histogram<a class="headerlink" href="#plotting-the-histogram" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># the histogram of the bootstrapped data (normalized data if density = True)
n, binsboot, patches = plt.hist(t, 50, density=True, facecolor=&#39;red&#39;, alpha=0.75)
# add a &#39;best fit&#39; line
y = norm.pdf(binsboot, np.mean(t), np.std(t))
lt = plt.plot(binsboot, y, &#39;b&#39;, linewidth=1)
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;Probability&#39;)
plt.grid(True)
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="the-bias-variance-tradeoff">
<h2>The bias-variance tradeoff<a class="headerlink" href="#the-bias-variance-tradeoff" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(\mathcal{D}\)</span> consisting of the data
<span class="math notranslate nohighlight">\(\mathbf{X}_\mathcal{D}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}\)</span>.</p>
<p>Let us assume that the true data is generated from a noisy model</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
\]</div>
<p>where <span class="math notranslate nohighlight">\(\epsilon\)</span> is normally distributed with mean zero and standard deviation <span class="math notranslate nohighlight">\(\sigma^2\)</span>.</p>
<p>In our derivation of the ordinary least squares method we defined then
an approximation to the function <span class="math notranslate nohighlight">\(f\)</span> in terms of the parameters
<span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> and the design matrix <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span> which embody our model,
that is <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\theta}\)</span>.</p>
<p>Thereafter we found the parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> by optimizing the means squared error via the so-called cost function</p>
<div class="math notranslate nohighlight">
\[
C(\boldsymbol{X},\boldsymbol{\theta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
\]</div>
<p>We can rewrite this as</p>
<div class="math notranslate nohighlight">
\[
\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.
\]</div>
<p>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 <span class="math notranslate nohighlight">\(\boldsymbol{\epsilon}\)</span>.</p>
<p>To derive this equation, we need to recall that the variance of <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> and <span class="math notranslate nohighlight">\(\boldsymbol{\epsilon}\)</span> are both equal to <span class="math notranslate nohighlight">\(\sigma^2\)</span>. The mean value of <span class="math notranslate nohighlight">\(\boldsymbol{\epsilon}\)</span> is by definition equal to zero. Furthermore, the function <span class="math notranslate nohighlight">\(f\)</span> is not a stochastics variable, idem for <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}\)</span>.
We use a more compact notation in terms of the expectation value</p>
<div class="math notranslate nohighlight">
\[
\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
\]</div>
<p>and adding and subtracting <span class="math notranslate nohighlight">\(\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\)</span> we get</p>
<div class="math notranslate nohighlight">
\[
\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],
\]</div>
<p>which, using the abovementioned expectation values can be rewritten as</p>
<div class="math notranslate nohighlight">
\[
\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,
\]</div>
<p>that is the rewriting in terms of the so-called bias, the variance of the model <span class="math notranslate nohighlight">\(\boldsymbol{\tilde{y}}\)</span> and the variance of <span class="math notranslate nohighlight">\(\boldsymbol{\epsilon}\)</span>.</p>
</section>
<section id="a-way-to-read-the-bias-variance-tradeoff">
<h2>A way to Read the Bias-Variance Tradeoff<a class="headerlink" href="#a-way-to-read-the-bias-variance-tradeoff" title="Link to this heading">#</a></h2>
<!-- dom:FIGURE: [figures/BiasVariance.png, width=600 frac=0.9] -->
<!-- begin figure -->
<p><img src="figures/BiasVariance.png" width="600"><p style="font-size: 0.9em"><i>Figure 1: </i></p></p>
<!-- end figure --></section>
<section id="example-code-for-bias-variance-tradeoff">
<h2>Example code for Bias-Variance tradeoff<a class="headerlink" href="#example-code-for-bias-variance-tradeoff" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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(&#39;Error:&#39;, error)
print(&#39;Bias^2:&#39;, bias)
print(&#39;Var:&#39;, variance)
print(&#39;{} &gt;= {} + {} = {}&#39;.format(error, bias, variance, bias+variance))
plt.plot(x[::5, :], y[::5, :], label=&#39;f(x)&#39;)
plt.scatter(x_test, y_test, label=&#39;Data points&#39;)
plt.scatter(x_test, np.mean(y_pred, axis=1), label=&#39;Pred&#39;)
plt.legend()
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="understanding-what-happens">
<h2>Understanding what happens<a class="headerlink" href="#understanding-what-happens" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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(&#39;Polynomial degree:&#39;, degree)
print(&#39;Error:&#39;, error[degree])
print(&#39;Bias^2:&#39;, bias[degree])
print(&#39;Var:&#39;, variance[degree])
print(&#39;{} &gt;= {} + {} = {}&#39;.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
plt.plot(polydegree, error, label=&#39;Error&#39;)
plt.plot(polydegree, bias, label=&#39;bias&#39;)
plt.plot(polydegree, variance, label=&#39;Variance&#39;)
plt.legend()
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="summing-up">
<h2>Summing up<a class="headerlink" href="#summing-up" title="Link to this heading">#</a></h2>
<p>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).</p>
<p>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 <span class="math notranslate nohighlight">\(Var(\epsilon)\)</span>, the irreducible error.</p>
<p>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.</p>
<p>You may also find this recent <a class="reference external" href="https://www.pnas.org/content/116/32/15849">article</a> of interest.</p>
</section>
<section id="another-example-from-scikit-learn-s-repository">
<h2>Another Example from Scikit-Learns Repository<a class="headerlink" href="#another-example-from-scikit-learn-s-repository" title="Link to this heading">#</a></h2>
<p>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 <strong>underfitting</strong>. A polynomial of degree 4
approximates the true function almost perfectly. However, for higher degrees
the model will <strong>overfit</strong> 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.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>
#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([(&quot;polynomial_features&quot;, polynomial_features),
(&quot;linear_regression&quot;, linear_regression)])
pipeline.fit(X[:, np.newaxis], y)
# Evaluate the models using crossvalidation
scores = cross_val_score(pipeline, X[:, np.newaxis], y,
scoring=&quot;neg_mean_squared_error&quot;, cv=10)
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=&quot;Model&quot;)
plt.plot(X_test, true_fun(X_test), label=&quot;True function&quot;)
plt.scatter(X, y, edgecolor=&#39;b&#39;, s=20, label=&quot;Samples&quot;)
plt.xlabel(&quot;x&quot;)
plt.ylabel(&quot;y&quot;)
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc=&quot;best&quot;)
plt.title(&quot;Degree {}\nMSE = {:.2e}(+/- {:.2e})&quot;.format(
degrees[i], -scores.mean(), scores.std()))
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="various-steps-in-cross-validation">
<h2>Various steps in cross-validation<a class="headerlink" href="#various-steps-in-cross-validation" title="Link to this heading">#</a></h2>
<p>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 <span class="math notranslate nohighlight">\(k\)</span>-fold cross-validation structures the data splitting. The
samples are divided into <span class="math notranslate nohighlight">\(k\)</span> 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 <span class="math notranslate nohighlight">\(k\)</span> subsets
involves a degree of randomness. This may be fully excluded when
choosing <span class="math notranslate nohighlight">\(k=n\)</span>. This particular case is referred to as leave-one-out
cross-validation (LOOCV).</p>
</section>
<section id="cross-validation-in-brief">
<h2>Cross-validation in brief<a class="headerlink" href="#cross-validation-in-brief" title="Link to this heading">#</a></h2>
<p>For the various values of <span class="math notranslate nohighlight">\(k\)</span></p>
<ol class="arabic simple">
<li><p>shuffle the dataset randomly.</p></li>
<li><p>Split the dataset into <span class="math notranslate nohighlight">\(k\)</span> groups.</p></li>
<li><p>For each unique group:</p></li>
</ol>
<p>a. Decide which group to use as set for test data</p>
<p>b. Take the remaining groups as a training data set</p>
<p>c. Fit a model on the training set and evaluate it on the test set</p>
<p>d. Retain the evaluation score and discard the model</p>
<ol class="arabic simple" start="5">
<li><p>Summarize the model using the sample of model evaluation scores</p></li>
</ol>
</section>
<section id="code-example-for-cross-validation-and-k-fold-cross-validation">
<h2>Code Example for Cross-validation and <span class="math notranslate nohighlight">\(k\)</span>-fold Cross-validation<a class="headerlink" href="#code-example-for-cross-validation-and-k-fold-cross-validation" title="Link to this heading">#</a></h2>
<p>The code here uses Ridge regression with cross-validation (CV) resampling and <span class="math notranslate nohighlight">\(k\)</span>-fold CV in order to fit a specific polynomial.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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=&#39;neg_mean_squared_error&#39;, 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 = &#39;cross_val_score&#39;)
plt.plot(np.log10(lambdas), estimated_mse_KFold, &#39;r--&#39;, label = &#39;KFold&#39;)
plt.xlabel(&#39;log10(lambda)&#39;)
plt.ylabel(&#39;mse&#39;)
plt.legend()
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="more-examples-on-bootstrap-and-cross-validation-and-errors">
<h2>More examples on bootstrap and cross-validation and errors<a class="headerlink" href="#more-examples-on-bootstrap-and-cross-validation-and-errors" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># 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 = &quot;Results&quot;
FIGURE_ID = &quot;Results/FigureFiles&quot;
DATA_ID = &quot;DataFiles/&quot;
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) + &quot;.png&quot;, format=&#39;png&#39;)
infile = open(data_path(&quot;EoS.csv&quot;),&#39;r&#39;)
# Read the EoS data as csv file and organize the data into two arrays with density and energies
EoS = pd.read_csv(infile, names=(&#39;Density&#39;, &#39;Energy&#39;))
EoS[&#39;Energy&#39;] = pd.to_numeric(EoS[&#39;Energy&#39;], errors=&#39;coerce&#39;)
EoS = EoS.dropna()
Energies = EoS[&#39;Energy&#39;]
Density = EoS[&#39;Density&#39;]
# 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(&quot;Degree of polynomial: %3d&quot;% polynomial[polydegree])
print(&quot;Mean squared error on training data: %.8f&quot; % trainingerror[polydegree])
print(&quot;Mean squared error on test data: %.8f&quot; % testerror[polydegree])
plt.plot(polynomial, np.log10(trainingerror), label=&#39;Training Error&#39;)
plt.plot(polynomial, np.log10(testerror), label=&#39;Test Error&#39;)
plt.xlabel(&#39;Polynomial degree&#39;)
plt.ylabel(&#39;log10[MSE]&#39;)
plt.legend()
plt.show()
</pre></div>
</div>
</div>
</div>
<p>Note that we kept the intercept column in the fitting here. This means that we need to set the <strong>intercept</strong> in the call to the <strong>Scikit-Learn</strong> function as <strong>False</strong>. Alternatively, we could have set up the design matrix <span class="math notranslate nohighlight">\(X\)</span> without the first column of ones.</p>
</section>
<section id="the-same-example-but-now-with-cross-validation">
<h2>The same example but now with cross-validation<a class="headerlink" href="#the-same-example-but-now-with-cross-validation" title="Link to this heading">#</a></h2>
<p>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.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># 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 = &quot;Results&quot;
FIGURE_ID = &quot;Results/FigureFiles&quot;
DATA_ID = &quot;DataFiles/&quot;
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) + &quot;.png&quot;, format=&#39;png&#39;)
infile = open(data_path(&quot;EoS.csv&quot;),&#39;r&#39;)
# Read the EoS data as csv file and organize the data into two arrays with density and energies
EoS = pd.read_csv(infile, names=(&#39;Density&#39;, &#39;Energy&#39;))
EoS[&#39;Energy&#39;] = pd.to_numeric(EoS[&#39;Energy&#39;], errors=&#39;coerce&#39;)
EoS = EoS.dropna()
Energies = EoS[&#39;Energy&#39;]
Density = EoS[&#39;Density&#39;]
# 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=&#39;neg_mean_squared_error&#39;, cv=kfold)
#[:, np.newaxis]
estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
plt.plot(polynomial, np.log10(estimated_mse_sklearn), label=&#39;Test Error&#39;)
plt.xlabel(&#39;Polynomial degree&#39;)
plt.ylabel(&#39;log10[MSE]&#39;)
plt.legend()
plt.show()
</pre></div>
</div>
</div>
</div>
</section>
<section id="material-for-the-lab-sessions">
<h2>Material for the lab sessions<a class="headerlink" href="#material-for-the-lab-sessions" title="Link to this heading">#</a></h2>
<p>This week we will discuss during the first hour of each lab session
some technicalities related to the project and methods for updating
the learning like ADAgrad, RMSprop and ADAM. As teaching material, see
the jupyter-notebook from week 37 (September 12-16).</p>
<p>For the lab session, the following video on cross validation (from 2024), could be helpful, see <a class="reference external" href="https://www.youtube.com/watch?v=T9jjWsmsd1o">https://www.youtube.com/watch?v=T9jjWsmsd1o</a></p>
<p>See also video on ADAgrad, RMSprop and ADAM (material from last week not covered during lecture) at <a class="reference external" href="https://youtu.be/J_41Hld6tTU">https://youtu.be/J_41Hld6tTU</a></p>
</section>
</section>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
name: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</article>
<footer class="prev-next-footer d-print-none">
<div class="prev-next-area">
<a class="left-prev"
href="exercisesweek38.html"
title="previous page">
<i class="fa-solid fa-angle-left"></i>
<div class="prev-next-info">
<p class="prev-next-subtitle">previous</p>
<p class="prev-next-title">Exercises week 38</p>
</div>
</a>
<a class="right-next"
href="exercisesweek39.html"
title="next page">
<div class="prev-next-info">
<p class="prev-next-subtitle">next</p>
<p class="prev-next-title">Exercises week 39</p>
</div>
<i class="fa-solid fa-angle-right"></i>
</a>
</div>
</footer>
</div>
<div class="bd-sidebar-secondary bd-toc"><div class="sidebar-secondary-items sidebar-secondary__inner">
<div class="sidebar-secondary-item">
<div class="page-toc tocsection onthispage">
<i class="fa-solid fa-list"></i> Contents
</div>
<nav class="bd-toc-nav page-toc">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#plans-for-week-38-lecture-monday-september-15">Plans for week 38, lecture Monday September 15</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#readings-and-videos">Readings and Videos</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#linking-the-regression-analysis-with-a-statistical-interpretation">Linking the regression analysis with a statistical interpretation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#assumptions-made">Assumptions made</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#expectation-value-and-variance">Expectation value and variance</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#expectation-value-and-variance-for-boldsymbol-theta">Expectation value and variance for <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#deriving-ols-from-a-probability-distribution">Deriving OLS from a probability distribution</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#independent-and-identically-distributed-iid">Independent and Identically Distributed (iid)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#maximum-likelihood-estimation-mle">Maximum Likelihood Estimation (MLE)</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-new-cost-function">A new Cost Function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#why-resampling-methods">Why resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods">Resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-approaches-can-be-computationally-expensive">Resampling approaches can be computationally expensive</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">Why resampling methods ?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#statistical-analysis">Statistical analysis</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">Resampling methods</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap">Resampling methods: Bootstrap</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-central-limit-theorem">The Central Limit Theorem</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#finding-the-limit">Finding the Limit</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#rewriting-the-delta-function">Rewriting the <span class="math notranslate nohighlight">\(\delta\)</span>-function</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#identifying-terms">Identifying Terms</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#wrapping-it-up">Wrapping it up</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#confidence-intervals">Confidence Intervals</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#standard-approach-based-on-the-normal-distribution">Standard Approach based on the Normal Distribution</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-background">Resampling methods: Bootstrap background</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-more-bootstrap-background">Resampling methods: More Bootstrap background</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-approach">Resampling methods: Bootstrap approach</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#resampling-methods-bootstrap-steps">Resampling methods: Bootstrap steps</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example-for-the-bootstrap-method">Code example for the Bootstrap method</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#plotting-the-histogram">Plotting the Histogram</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-bias-variance-tradeoff">The bias-variance tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#a-way-to-read-the-bias-variance-tradeoff">A way to Read the Bias-Variance Tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#example-code-for-bias-variance-tradeoff">Example code for Bias-Variance tradeoff</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#understanding-what-happens">Understanding what happens</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#summing-up">Summing up</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#another-example-from-scikit-learn-s-repository">Another Example from Scikit-Learns Repository</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#various-steps-in-cross-validation">Various steps in cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#cross-validation-in-brief">Cross-validation in brief</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#code-example-for-cross-validation-and-k-fold-cross-validation">Code Example for Cross-validation and <span class="math notranslate nohighlight">\(k\)</span>-fold Cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-examples-on-bootstrap-and-cross-validation-and-errors">More examples on bootstrap and cross-validation and errors</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#the-same-example-but-now-with-cross-validation">The same example but now with cross-validation</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#material-for-the-lab-sessions">Material for the lab sessions</a></li>
</ul>
</nav></div>
</div></div>
</div>
<footer class="bd-footer-content">
<div class="bd-footer-content__inner container">
<div class="footer-item">
<p class="component-author">
By Morten Hjorth-Jensen
</p>
</div>
<div class="footer-item">
<p class="copyright">
© Copyright 2023.
<br/>
</p>
</div>
<div class="footer-item">
</div>
<div class="footer-item">
</div>
</div>
</footer>
</main>
</div>
</div>
<!-- Scripts loaded after <body> so the DOM is not blocked -->
<script src="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b"></script>
<footer class="bd-footer">
</footer>
</body>
</html>