Files
FYS-STK4155/doc/pub/week38/html/week38.html
T
Morten Hjorth-Jensen 8dd0f7db27 update. week 38
2025-09-14 09:04:00 +02:00

1847 lines
114 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week38.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week38 --no_mako
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 38: Statistical analysis, bias-variance tradeoff and resampling methods">
<title>Week 38: Statistical analysis, bias-variance tradeoff and resampling methods</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { font-size: 1.2em; color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
border: 1px solid #cfcfcf;
border-radius: 2px;
line-height: 1.21429em;
}
div.cell {
width: 100%;
padding: 5px 5px 5px 0;
margin: 0;
outline: none;
}
div.input {
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.inner_cell {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
box-flex: 1;
flex: 1;
}
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 4px;
background: #f7f7f7;
line-height: 1.21429em;
}
div.input_area > div.highlight {
margin: .4em;
border: none;
padding: 0;
background-color: transparent;
}
div.output_wrapper {
position: relative;
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
.output {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
div.output_area {
padding: 0;
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_subarea {
padding: .4em .4em 0 .4em;
box-flex: 1;
flex: 1;
}
div.output_text {
text-align: left;
color: #000;
line-height: 1.21429em;
}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 38, lecture Monday September 15',
2,
None,
'plans-for-week-38-lecture-monday-september-15'),
('Readings and Videos', 2, None, 'readings-and-videos'),
('Linking the regression analysis with a statistical '
'interpretation',
2,
None,
'linking-the-regression-analysis-with-a-statistical-interpretation'),
('Assumptions made', 2, None, 'assumptions-made'),
('Expectation value and variance',
2,
None,
'expectation-value-and-variance'),
('Expectation value and variance for $\\boldsymbol{\\beta}$',
2,
None,
'expectation-value-and-variance-for-boldsymbol-beta'),
('Deriving OLS from a probability distribution',
2,
None,
'deriving-ols-from-a-probability-distribution'),
('Independent and Identically Distributed (iid)',
2,
None,
'independent-and-identically-distributed-iid'),
('Maximum Likelihood Estimation (MLE)',
2,
None,
'maximum-likelihood-estimation-mle'),
('A new Cost Function', 2, None, 'a-new-cost-function'),
('Why resampling methods', 2, None, 'why-resampling-methods'),
('Resampling methods', 2, None, 'resampling-methods'),
('Resampling approaches can be computationally expensive',
2,
None,
'resampling-approaches-can-be-computationally-expensive'),
('Why resampling methods ?', 2, None, 'why-resampling-methods'),
('Statistical analysis', 2, None, 'statistical-analysis'),
('Resampling methods', 2, None, 'resampling-methods'),
('Resampling methods: Bootstrap',
2,
None,
'resampling-methods-bootstrap'),
('The Central Limit Theorem',
2,
None,
'the-central-limit-theorem'),
('Finding the Limit', 2, None, 'finding-the-limit'),
('Rewriting the $\\delta$-function',
2,
None,
'rewriting-the-delta-function'),
('Identifying Terms', 2, None, 'identifying-terms'),
('Wrapping it up', 2, None, 'wrapping-it-up'),
('Confidence Intervals', 2, None, 'confidence-intervals'),
('Standard Approach based on the Normal Distribution',
2,
None,
'standard-approach-based-on-the-normal-distribution'),
('Resampling methods: Bootstrap background',
2,
None,
'resampling-methods-bootstrap-background'),
('Resampling methods: More Bootstrap background',
2,
None,
'resampling-methods-more-bootstrap-background'),
('Resampling methods: Bootstrap approach',
2,
None,
'resampling-methods-bootstrap-approach'),
('Resampling methods: Bootstrap steps',
2,
None,
'resampling-methods-bootstrap-steps'),
('Code example for the Bootstrap method',
2,
None,
'code-example-for-the-bootstrap-method'),
('Plotting the Histogram', 2, None, 'plotting-the-histogram'),
('The bias-variance tradeoff',
2,
None,
'the-bias-variance-tradeoff'),
('A way to Read the Bias-Variance Tradeoff',
2,
None,
'a-way-to-read-the-bias-variance-tradeoff'),
('Example code for Bias-Variance tradeoff',
2,
None,
'example-code-for-bias-variance-tradeoff'),
('Understanding what happens',
2,
None,
'understanding-what-happens'),
('Summing up', 2, None, 'summing-up'),
("Another Example from Scikit-Learn's Repository",
2,
None,
'another-example-from-scikit-learn-s-repository'),
('Various steps in cross-validation',
2,
None,
'various-steps-in-cross-validation'),
('Cross-validation in brief',
2,
None,
'cross-validation-in-brief'),
('Code Example for Cross-validation and $k$-fold '
'Cross-validation',
2,
None,
'code-example-for-cross-validation-and-k-fold-cross-validation'),
('More examples on bootstrap and cross-validation and errors',
2,
None,
'more-examples-on-bootstrap-and-cross-validation-and-errors'),
('The same example but now with cross-validation',
2,
None,
'the-same-example-but-now-with-cross-validation'),
('Material for the lab sessions',
2,
None,
'material-for-the-lab-sessions')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center>
<h1>Week 38: Statistical analysis, bias-variance tradeoff and resampling methods</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b>
</center>
<!-- institution -->
<center>
<b>Department of Physics and Center for Computing in Science Education, University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>September 15-19, 2025</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plans-for-week-38-lecture-monday-september-15">Plans for week 38, lecture Monday September 15 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Material for the lecture on Monday September 15</b>
<p>
<ol>
<li> Statistical interpretation of Ridge and Lasso regression</li>
<li> Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff (this may partly be discussed during the exercise sessions as well.</li>
<li> 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 href="https://youtu.be/J_41Hld6tTU" target="_blank"><tt>https://youtu.be/J_41Hld6tTU</tt></a>
<!-- * <a href="https://youtu.be/omLmp_kkie0" target="_blank">Video of Lecture</a> -->
<!-- * <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember9.pdf" target="_blank">Whiteboard notes</a> --></li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="readings-and-videos">Readings and Videos </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ol>
<li> Raschka et al, pages 175-192</li>
<li> Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). See <a href="https://link.springer.com/book/10.1007/978-0-387-84858-7" target="_blank"><tt>https://link.springer.com/book/10.1007/978-0-387-84858-7</tt></a>.</li>
<li> <a href="https://www.youtube.com/watch?v=EuBBz3bI-aA" target="_blank">Video on bias-variance tradeoff</a></li>
<li> <a href="https://www.youtube.com/watch?v=Xz0x-8-cgaQ" target="_blank">Video on Bootstrapping</a></li>
<li> <a href="https://www.youtube.com/watch?v=fSytzGwwBVw" target="_blank">Video on cross validation</a></li>
</ol>
<p>For the lab session, the following video on cross validation (from 2024), could be helpful, see <a href="https://www.youtube.com/watch?v=T9jjWsmsd1o" target="_blank"><tt>https://www.youtube.com/watch?v=T9jjWsmsd1o</tt></a></p>
</div>
<!-- !split -->
<h2 id="linking-the-regression-analysis-with-a-statistical-interpretation">Linking the regression analysis with a statistical interpretation </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
\( \beta \).
</p>
<p>On of the advantages of doing linear regression is that we actually end up with
analytical expressions for several statistical quantities.
Standard least squares and Ridge regression allow us to
derive quantities like the variance and other expectation values in a
rather straightforward way.
</p>
<p>It is assumed that \( \varepsilon_i
\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
independent, i.e.:
</p>
$$
\begin{align*}
\mbox{Cov}(\varepsilon_{i_1},
\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
\end{align*}
$$
<p>The randomness of \( \varepsilon_i \) implies that
\( \mathbf{y}_i \) is also a random variable. In particular,
\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim
\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a
non-random scalar. To specify the parameters of the distribution of
\( \mathbf{y}_i \) we need to calculate its first two moments.
</p>
<p>Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The
notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the
row number \( i \) and perform a sum over all values \( p \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="assumptions-made">Assumptions made </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 \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
which describe our data
</p>
$$
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
$$
<p>We approximate this function with our model from the solution of the linear regression equations, that is our
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with
</p>
$$
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="expectation-value-and-variance">Expectation value and variance </h2>
<p>We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) </p>
$$
\begin{align*}
\mathbb{E}(y_i) & =
\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
\end{align*}
$$
<p>while
its variance is
</p>
$$
\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
$$
<p>Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="expectation-value-and-variance-for-boldsymbol-beta">Expectation value and variance for \( \boldsymbol{\beta} \) </h2>
<p>With the OLS expressions for the optimal parameters \( \boldsymbol{\hat{\beta}} \) we can evaluate the expectation value</p>
$$
\mathbb{E}(\boldsymbol{\hat{\beta}}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
$$
<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 \( \boldsymbol{\hat{\beta}} \) is</p>
$$
\begin{eqnarray*}
\mbox{Var}(\boldsymbol{\hat{\beta}}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
\\
& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
\\
% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
\\
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
% \\
% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
% \\
% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
\\
& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
\end{eqnarray*}
$$
<p>where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
variance of the estimate of the \( j \)-th regression coefficient:
\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). This may be used to
construct a confidence interval for the estimates.
</p>
<p>In a similar way, we can obtain analytical expressions for say the
expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
when we employ Ridge regression, allowing us again to define a confidence interval.
</p>
<p>It is rather straightforward to show that</p>
$$
\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
$$
<p>We see clearly that
\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased.
</p>
<p>We can also compute the variance as </p>
$$
\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
$$
<p>and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. </p>
<p>With this, we can compute the difference </p>
$$
\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
$$
<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 \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="deriving-ols-from-a-probability-distribution">Deriving OLS from a probability distribution </h2>
<p>Our basic assumption when we derived the OLS equations was to assume
that our output is determined by a given continuous function
\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal
distribution with zero mean value and an undetermined variance
\( \sigma^2 \).
</p>
<p>We found above that the outputs \( \boldsymbol{y} \) have a mean value given by
\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to
the design matrix are not stochastic variables, we can assume that the
probability distribution of our targets is also a normal distribution
but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a
single output \( y_i \) is given by the Gaussian distribution
</p>
$$
y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="independent-and-identically-distributed-iid">Independent and Identically Distributed (iid) </h2>
<p>We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution.
We define this distribution as
</p>
$$
p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
$$
<p>which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).</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 \( \boldsymbol{y} \) as the product of the single events, that is we have</p>
$$
p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
$$
<p>We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is
in case we have a simple one-dimensional input and output case
</p>
$$
\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
$$
<p>In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \).
We can now rewrite the above probability as
</p>
$$
p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
<p>It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="maximum-likelihood-estimation-mle">Maximum Likelihood Estimation (MLE) </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 \( \beta \) by
maximizing the above PDF. However, computing the derivatives of a
product function is cumbersome and can easily lead to overflow and/or
underflowproblems, with potentials for loss of numerical precision.
</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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-new-cost-function">A new Cost Function </h2>
<p>We could now define a new cost function to minimize, namely the negative logarithm of the above PDF</p>
$$
C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
$$
<p>which becomes</p>
$$
C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
$$
<p>Taking the derivative of the <em>new</em> cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely</p>
$$
\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
$$
<p>which leads to the well-known OLS equation for the optimal paramters \( \beta \)</p>
$$
\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
$$
<p>Next week we will make a similar analysis for Ridge and Lasso regression</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-resampling-methods">Why resampling methods </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>
<li> look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff</li>
<li> introduce resampling techniques like cross-validation, bootstrapping and jackknife and more</li>
</ol>
<p>and discuss how to select a given model (one of the difficult parts in machine learning).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods">Resampling methods </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<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>
<li> The <b>bootstrap method</b></li>
<li> and <b>Cross-Validation</b></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>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-approaches-can-be-computationally-expensive">Resampling approaches can be computationally expensive </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<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 model&#8217;s performance is
known as model assessment, whereas the process of selecting the proper
level of flexibility for a model is known as model selection. The
bootstrap is widely used.
</p>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-resampling-methods">Why resampling methods ? </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Statistical analysis</b>
<p>
<ul>
<li> 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.</li>
<li> The results can be analysed with the same statistical tools as we would use when analysing experimental data.</li>
<li> As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.</li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="statistical-analysis">Statistical analysis </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> As in other experiments, many numerical experiments have two classes of errors:</li>
<ul>
<li> Statistical errors</li>
<li> Systematical errors</li>
</ul>
<li> Statistical errors can be estimated using standard tools from statistics</li>
<li> Systematical errors are method specific and must be treated differently from case to case.</li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods">Resampling methods </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>
<li> prediction error or simply the <b>test error</b> \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the</li>
<li> training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.</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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods-bootstrap">Resampling methods: Bootstrap </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>Bootstrapping is a <a href="https://en.wikipedia.org/wiki/Nonparametric_statistics" target="_blank">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>
<li> The bootstrap is quite general, although there are some cases in which it fails.</li>
<li> 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.</li>
<li> It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.</li>
<li> It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).</li>
</ol>
</div>
<p>The textbook by <a href="https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A" target="_blank">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 href="https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317" target="_blank">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 <b>central limit theorem</b>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-central-limit-theorem">The Central Limit Theorem </h2>
<p>Suppose we have a PDF \( p(x) \) from which we generate a series \( N \)
of averages \( \mathbb{E}[x_i] \). Each mean value \( \mathbb{E}[x_i] \)
is viewed as the average of a specific measurement, e.g., throwing
dice 100 times and then taking the average value, or producing a certain
amount of random numbers.
For notational ease, we set \( \mathbb{E}[x_i]=x_i \) in the discussion
which follows. We do the same for \( \mathbb{E}[z]=z \).
</p>
<p>If we compute the mean \( z \) of \( m \) such mean values \( x_i \) </p>
$$
z=\frac{x_1+x_2+\dots+x_m}{m},
$$
<p>the question we pose is which is the PDF of the new variable \( z \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="finding-the-limit">Finding the Limit </h2>
<p>The probability of obtaining an average value \( z \) is the product of the
probabilities of obtaining arbitrary individual mean values \( x_i \),
but with the constraint that the average is \( z \). We can express this through
the following expression
</p>
$$
\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}),
$$
<p>where the \( \delta \)-function enbodies the constraint that the mean is \( z \).
All measurements that lead to each individual \( x_i \) are expected to
be independent, which in turn means that we can express \( \tilde{p} \) as the
product of individual \( p(x_i) \). The independence assumption is important in the derivation of the central limit theorem.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="rewriting-the-delta-function">Rewriting the \( \delta \)-function </h2>
<p>If we use the integral expression for the \( \delta \)-function</p>
$$
\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)},
$$
<p>and inserting \( e^{i\mu q-i\mu q} \) where \( \mu \) is the mean value
we arrive at
</p>
$$
\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,
$$
<p>with the integral over \( x \) resulting in</p>
$$
\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].
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="identifying-terms">Identifying Terms </h2>
<p>The second term on the rhs disappears since this is just the mean and
employing the definition of \( \sigma^2 \) we have
</p>
$$
\int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}=
1-\frac{q^2\sigma^2}{2m^2}+\dots,
$$
<p>resulting in </p>
$$
\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,
$$
<p>and in the limit \( m\rightarrow \infty \) we obtain </p>
$$
\tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})}
\exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)},
$$
<p>which is the normal distribution with variance
\( \sigma^2_m=\sigma^2/m \), where \( \sigma \) is the variance of the PDF \( p(x) \)
and \( \mu \) is also the mean of the PDF \( p(x) \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="wrapping-it-up">Wrapping it up </h2>
<p>Thus, the central limit theorem states that the PDF \( \tilde{p}(z) \) of
the average of \( m \) random values corresponding to a PDF \( p(x) \)
is a normal distribution whose mean is the
mean value of the PDF \( p(x) \) and whose variance is the variance
of the PDF \( p(x) \) divided by \( m \), the number of values used to compute \( z \).
</p>
<p>The central limit theorem leads to the well-known expression for the
standard deviation, given by
</p>
$$
\sigma_m=
\frac{\sigma}{\sqrt{m}}.
$$
<p>The latter is true only if the average value is known exactly. This is obtained in the limit
\( m\rightarrow \infty \) only. Because the mean and the variance are measured quantities we obtain
the familiar expression in statistics (the so-called Bessel correction)
</p>
$$
\sigma_m\approx
\frac{\sigma}{\sqrt{m-1}}.
$$
<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 \( x \) are independent
and identically distributed. This is obviously not always the
case. For example, the random numbers (or better pseudorandom numbers)
we generate in various calculations do always exhibit some
correlations.
</p>
<p>The theorem is satisfied by a large class of PDFs. Note however that for a
finite \( m \), it is not always possible to find a closed form /analytic expression for
\( \tilde{p}(x) \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="confidence-intervals">Confidence Intervals </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 \( \boldsymbol{\beta} \) from linear regression.
</p>
<p>With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we found
\( \mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta} \), which means that the estimator of the regression parameters is unbiased.
</p>
<p>In the exercises this week we show that the variance of the estimate of the \( j \)-th regression coefficient is
\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \).
</p>
<p>This quantity can be used to
construct a confidence interval for the estimates.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="standard-approach-based-on-the-normal-distribution">Standard Approach based on the Normal Distribution </h2>
<p>We will assume that the parameters \( \beta \) follow a normal
distribution. We can then define the confidence interval. Here we will be using as
shorthands \( \mu_{\beta} \) for the above mean value and \( \sigma_{\beta} \)
for the standard deviation. We have then a confidence interval
</p>
$$
\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right),
$$
<p>where \( z \) defines the level of certainty (or confidence). For a normal
distribution typical parameters are \( z=2.576 \) which corresponds to a
confidence of \( 99\% \) while \( z=1.96 \) corresponds to a confidence of
\( 95\% \). A confidence level of \( 95\% \) is commonly used and it is
normally referred to as a <em>two-sigmas</em> confidence level, that is we
approximate \( z\approx 2 \).
</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 href="https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A" target="_blank">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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods-bootstrap-background">Resampling methods: Bootstrap background </h2>
<p>Since \( \widehat{\beta} = \widehat{\beta}(\boldsymbol{X}) \) is a function of random variables,
\( \widehat{\beta} \) itself must be a random variable. Thus it has
a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
estimate \( p(\boldsymbol{t}) \) by the relative frequency of
\( \widehat{\beta} \). You can think of this as using a histogram
in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
estimators.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods-more-bootstrap-background">Resampling methods: More Bootstrap background </h2>
<p>In the case that \( \widehat{\beta} \) has
more than one component, and the components are independent, we use the
same estimator on each component separately. If the probability
density function of \( X_i \), \( p(x) \), had been known, then it would have
been straightforward to do this by:
</p>
<ol>
<li> Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).</li>
<li> Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).</li>
</ol>
<p>By repeated use of the above two points, many
estimates of \( \widehat{\beta} \) can be obtained. The
idea is to use the relative frequency of \( \widehat{\beta}^* \)
(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods-bootstrap-approach">Resampling methods: Bootstrap approach </h2>
<p>But
unless there is enough information available about the process that
generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general
unknown. Therefore, <a href="https://projecteuclid.org/euclid.aos/1176344552" target="_blank">Efron in 1979</a> asked the
question: What if we replace \( p(x) \) by the relative frequency
of the observation \( X_i \)?
</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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling-methods-bootstrap-steps">Resampling methods: Bootstrap steps </h2>
<p>The independent bootstrap works like this: </p>
<ol>
<li> Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).</li>
<li> Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).</li>
<li> Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).</li>
<li> Repeat this process \( k \) times.</li>
</ol>
<p>When you are done, you can draw a histogram of the relative frequency
of \( \widehat \beta^* \). This is your estimate of the probability
distribution \( p(t) \). Using this probability distribution you can
estimate any statistics thereof. In principle you never draw the
histogram of the relative frequency of \( \widehat{\beta}^* \). Instead
you use the estimators corresponding to the statistic of interest. For
example, if you are interested in estimating the variance of \( \widehat
\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values
\( \widehat \beta^* \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="code-example-for-the-bootstrap-method">Code example for the Bootstrap method </h2>
<p>The following code starts with a Gaussian distribution with mean value
\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data
used in the bootstrap analysis. The bootstrap analysis returns a data
set after a given number of bootstrap operations (as many as we have
data points). This data set consists of estimated mean values for each
bootstrap operation. The histogram generated by the bootstrap method
shows that the distribution for these mean values is also a Gaussian,
centered around the mean value \( \mu=100 \) but with standard deviation
\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in
this case the same as the number of original data points). The value
of the standard deviation is what we expect from the central limit
theorem.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">time</span> <span style="color: #008000; font-weight: bold">import</span> time
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy.stats</span> <span style="color: #008000; font-weight: bold">import</span> norm
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic"># Returns mean of bootstrap samples </span>
<span style="color: #408080; font-style: italic"># Bootstrap algorithm</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">bootstrap</span>(data, datapoints):
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(datapoints)
n <span style="color: #666666">=</span> <span style="color: #008000">len</span>(data)
<span style="color: #408080; font-style: italic"># non-parametric bootstrap </span>
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(datapoints):
t[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(data[np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randint(<span style="color: #666666">0</span>,n,n)])
<span style="color: #408080; font-style: italic"># analysis </span>
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Bootstrap Statistics :&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;original bias std. error&quot;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;</span><span style="color: #BB6688; font-weight: bold">%8g</span><span style="color: #BA2121"> </span><span style="color: #BB6688; font-weight: bold">%8g</span><span style="color: #BA2121"> </span><span style="color: #BB6688; font-weight: bold">%14g</span><span style="color: #BA2121"> </span><span style="color: #BB6688; font-weight: bold">%15g</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> (np<span style="color: #666666">.</span>mean(data), np<span style="color: #666666">.</span>std(data),np<span style="color: #666666">.</span>mean(t),np<span style="color: #666666">.</span>std(t)))
<span style="color: #008000; font-weight: bold">return</span> t
<span style="color: #408080; font-style: italic"># We set the mean value to 100 and the standard deviation to 15</span>
mu, sigma <span style="color: #666666">=</span> <span style="color: #666666">100</span>, <span style="color: #666666">15</span>
datapoints <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
<span style="color: #408080; font-style: italic"># We generate random numbers according to the normal distribution</span>
x <span style="color: #666666">=</span> mu <span style="color: #666666">+</span> sigma<span style="color: #666666">*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(datapoints)
<span style="color: #408080; font-style: italic"># bootstrap returns the data sample </span>
t <span style="color: #666666">=</span> bootstrap(x, datapoints)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>We see that our new variance and from that the standard deviation, agrees with the central limit theorem.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plotting-the-histogram">Plotting the Histogram </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># the histogram of the bootstrapped data (normalized data if density = True)</span>
n, binsboot, patches <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>hist(t, <span style="color: #666666">50</span>, density<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, facecolor<span style="color: #666666">=</span><span style="color: #BA2121">&#39;red&#39;</span>, alpha<span style="color: #666666">=0.75</span>)
<span style="color: #408080; font-style: italic"># add a &#39;best fit&#39; line </span>
y <span style="color: #666666">=</span> norm<span style="color: #666666">.</span>pdf(binsboot, np<span style="color: #666666">.</span>mean(t), np<span style="color: #666666">.</span>std(t))
lt <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>plot(binsboot, y, <span style="color: #BA2121">&#39;b&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Probability&#39;</span>)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-bias-variance-tradeoff">The bias-variance tradeoff </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 \( \mathcal{D} \) consisting of the data
\( \mathbf{X}_\mathcal{D}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
</p>
<p>Let us assume that the true data is generated from a noisy model</p>
$$
\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
$$
<p>where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).</p>
<p>In our derivation of the ordinary least squares method we defined then
an approximation to the function \( f \) in terms of the parameters
\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
</p>
<p>Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function</p>
$$
C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
$$
<p>We can rewrite this as </p>
$$
\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.
$$
<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 \( \boldsymbol{\epsilon} \).
</p>
<p>To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
We use a more compact notation in terms of the expectation value
</p>
$$
\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
$$
<p>and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get</p>
$$
\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],
$$
<p>which, using the abovementioned expectation values can be rewritten as </p>
$$
\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,
$$
<p>that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-way-to-read-the-bias-variance-tradeoff">A way to Read the Bias-Variance Tradeoff </h2>
<br/><br/>
<center>
<p><img src="figures/BiasVariance.png" width="600" align="bottom"></p>
</center>
<br/><br/>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="example-code-for-bias-variance-tradeoff">Example code for Bias-Variance tradeoff </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression, Ridge, Lasso
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> make_pipeline
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">2018</span>)
n <span style="color: #666666">=</span> <span style="color: #666666">500</span>
n_boostraps <span style="color: #666666">=</span> <span style="color: #666666">100</span>
degree <span style="color: #666666">=</span> <span style="color: #666666">18</span> <span style="color: #408080; font-style: italic"># A quite high value, just to show.</span>
noise <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
<span style="color: #408080; font-style: italic"># Make data set.</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-1</span>, <span style="color: #666666">3</span>, n)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(<span style="color: #666666">0</span>, <span style="color: #666666">0.1</span>, x<span style="color: #666666">.</span>shape)
<span style="color: #408080; font-style: italic"># Hold out some test data that is never used in training.</span>
x_train, x_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(x, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># Combine x transformation and model into one operation.</span>
<span style="color: #408080; font-style: italic"># Not neccesary, but convenient.</span>
model <span style="color: #666666">=</span> make_pipeline(PolynomialFeatures(degree<span style="color: #666666">=</span>degree), LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>))
<span style="color: #408080; font-style: italic"># The following (m x n_bootstraps) matrix holds the column vectors y_pred</span>
<span style="color: #408080; font-style: italic"># for each bootstrap iteration.</span>
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty((y_test<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], n_boostraps))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_boostraps):
x_, y_ <span style="color: #666666">=</span> resample(x_train, y_train)
<span style="color: #408080; font-style: italic"># Evaluate the new model on the same test data each time.</span>
y_pred[:, i] <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(x_, y_)<span style="color: #666666">.</span>predict(x_test)<span style="color: #666666">.</span>ravel()
<span style="color: #408080; font-style: italic"># Note: Expectations and variances taken w.r.t. different training</span>
<span style="color: #408080; font-style: italic"># data sets, hence the axis=1. Subsequent means are taken across the test data</span>
<span style="color: #408080; font-style: italic"># set in order to obtain a total value, but before this we have error/bias/variance</span>
<span style="color: #408080; font-style: italic"># calculated per data point in the test set.</span>
<span style="color: #408080; font-style: italic"># Note 2: The use of keepdims=True is important in the calculation of bias as this </span>
<span style="color: #408080; font-style: italic"># maintains the column vector form. Dropping this yields very unexpected results.</span>
error <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> y_pred)<span style="color: #666666">**2</span>, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( (y_test <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>))<span style="color: #666666">**2</span> )
variance <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>var(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Error:&#39;</span>, error)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Bias^2:&#39;</span>, bias)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Var:&#39;</span>, variance)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> &gt;= </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> + </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">.</span>format(error, bias, variance, bias<span style="color: #666666">+</span>variance))
plt<span style="color: #666666">.</span>plot(x[::<span style="color: #666666">5</span>, :], y[::<span style="color: #666666">5</span>, :], label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;f(x)&#39;</span>)
plt<span style="color: #666666">.</span>scatter(x_test, y_test, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Data points&#39;</span>)
plt<span style="color: #666666">.</span>scatter(x_test, np<span style="color: #666666">.</span>mean(y_pred, axis<span style="color: #666666">=1</span>), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Pred&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="understanding-what-happens">Understanding what happens </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression, Ridge, Lasso
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> make_pipeline
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">2018</span>)
n <span style="color: #666666">=</span> <span style="color: #666666">40</span>
n_boostraps <span style="color: #666666">=</span> <span style="color: #666666">100</span>
maxdegree <span style="color: #666666">=</span> <span style="color: #666666">14</span>
<span style="color: #408080; font-style: italic"># Make data set.</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-3</span>, <span style="color: #666666">3</span>, n)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(<span style="color: #666666">0</span>, <span style="color: #666666">0.1</span>, x<span style="color: #666666">.</span>shape)
error <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
variance <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
polydegree <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
x_train, x_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(x, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(maxdegree):
model <span style="color: #666666">=</span> make_pipeline(PolynomialFeatures(degree<span style="color: #666666">=</span>degree), LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>))
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty((y_test<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], n_boostraps))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_boostraps):
x_, y_ <span style="color: #666666">=</span> resample(x_train, y_train)
y_pred[:, i] <span style="color: #666666">=</span> model<span style="color: #666666">.</span>fit(x_, y_)<span style="color: #666666">.</span>predict(x_test)<span style="color: #666666">.</span>ravel()
polydegree[degree] <span style="color: #666666">=</span> degree
error[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> y_pred)<span style="color: #666666">**2</span>, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
bias[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( (y_test <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>))<span style="color: #666666">**2</span> )
variance[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>var(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Polynomial degree:&#39;</span>, degree)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Error:&#39;</span>, error[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Bias^2:&#39;</span>, bias[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Var:&#39;</span>, variance[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> &gt;= </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> + </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">.</span>format(error[degree], bias[degree], variance[degree], bias[degree]<span style="color: #666666">+</span>variance[degree]))
plt<span style="color: #666666">.</span>plot(polydegree, error, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Error&#39;</span>)
plt<span style="color: #666666">.</span>plot(polydegree, bias, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;bias&#39;</span>)
plt<span style="color: #666666">.</span>plot(polydegree, variance, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Variance&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split -->
<h2 id="summing-up">Summing up </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 \( Var(\epsilon) \), 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 href="https://www.pnas.org/content/116/32/15849" target="_blank">article</a> of interest.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="another-example-from-scikit-learn-s-repository">Another Example from Scikit-Learn's Repository </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 <b>underfitting</b>. A polynomial of degree 4
approximates the true function almost perfectly. However, for higher degrees
the model will <b>overfit</b> 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>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic">#print(__doc__)</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> Pipeline
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_val_score
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">true_fun</span>(X):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>cos(<span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>pi <span style="color: #666666">*</span> X)
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">0</span>)
n_samples <span style="color: #666666">=</span> <span style="color: #666666">30</span>
degrees <span style="color: #666666">=</span> [<span style="color: #666666">1</span>, <span style="color: #666666">4</span>, <span style="color: #666666">15</span>]
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sort(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n_samples))
y <span style="color: #666666">=</span> true_fun(X) <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(n_samples) <span style="color: #666666">*</span> <span style="color: #666666">0.1</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">14</span>, <span style="color: #666666">5</span>))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(degrees)):
ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">1</span>, <span style="color: #008000">len</span>(degrees), i <span style="color: #666666">+</span> <span style="color: #666666">1</span>)
plt<span style="color: #666666">.</span>setp(ax, xticks<span style="color: #666666">=</span>(), yticks<span style="color: #666666">=</span>())
polynomial_features <span style="color: #666666">=</span> PolynomialFeatures(degree<span style="color: #666666">=</span>degrees[i],
include_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
linear_regression <span style="color: #666666">=</span> LinearRegression()
pipeline <span style="color: #666666">=</span> Pipeline([(<span style="color: #BA2121">&quot;polynomial_features&quot;</span>, polynomial_features),
(<span style="color: #BA2121">&quot;linear_regression&quot;</span>, linear_regression)])
pipeline<span style="color: #666666">.</span>fit(X[:, np<span style="color: #666666">.</span>newaxis], y)
<span style="color: #408080; font-style: italic"># Evaluate the models using crossvalidation</span>
scores <span style="color: #666666">=</span> cross_val_score(pipeline, X[:, np<span style="color: #666666">.</span>newaxis], y,
scoring<span style="color: #666666">=</span><span style="color: #BA2121">&quot;neg_mean_squared_error&quot;</span>, cv<span style="color: #666666">=10</span>)
X_test <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">100</span>)
plt<span style="color: #666666">.</span>plot(X_test, pipeline<span style="color: #666666">.</span>predict(X_test[:, np<span style="color: #666666">.</span>newaxis]), label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Model&quot;</span>)
plt<span style="color: #666666">.</span>plot(X_test, true_fun(X_test), label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;True function&quot;</span>)
plt<span style="color: #666666">.</span>scatter(X, y, edgecolor<span style="color: #666666">=</span><span style="color: #BA2121">&#39;b&#39;</span>, s<span style="color: #666666">=20</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Samples&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;x&quot;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;y&quot;</span>)
plt<span style="color: #666666">.</span>xlim((<span style="color: #666666">0</span>, <span style="color: #666666">1</span>))
plt<span style="color: #666666">.</span>ylim((<span style="color: #666666">-2</span>, <span style="color: #666666">2</span>))
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;best&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Degree </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">MSE = </span><span style="color: #BB6688; font-weight: bold">{:.2e}</span><span style="color: #BA2121">(+/- </span><span style="color: #BB6688; font-weight: bold">{:.2e}</span><span style="color: #BA2121">)&quot;</span><span style="color: #666666">.</span>format(
degrees[i], <span style="color: #666666">-</span>scores<span style="color: #666666">.</span>mean(), scores<span style="color: #666666">.</span>std()))
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split -->
<h2 id="various-steps-in-cross-validation">Various steps in cross-validation </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 \( k \)-fold cross-validation structures the data splitting. The
samples are divided into \( k \) more or less equally sized exhaustive and
mutually exclusive subsets. In turn (at each split) one of these
subsets plays the role of the test set while the union of the
remaining subsets constitutes the training set. Such a splitting
warrants a balanced representation of each sample in both training and
test set over the splits. Still the division into the \( k \) subsets
involves a degree of randomness. This may be fully excluded when
choosing \( k=n \). This particular case is referred to as leave-one-out
cross-validation (LOOCV).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cross-validation-in-brief">Cross-validation in brief </h2>
<p>For the various values of \( k \)</p>
<ol>
<li> shuffle the dataset randomly.</li>
<li> Split the dataset into \( k \) groups.</li>
<li> For each unique group:
<ol type="a"></li>
<li> Decide which group to use as set for test data</li>
<li> Take the remaining groups as a training data set</li>
<li> Fit a model on the training set and evaluate it on the test set</li>
<li> Retain the evaluation score and discard the model</li>
</ol>
<li> Summarize the model using the sample of model evaluation scores</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="code-example-for-cross-validation-and-k-fold-cross-validation">Code Example for Cross-validation and \( k \)-fold Cross-validation </h2>
<p>The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. </p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> KFold
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> Ridge
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_val_score
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">3155</span>)
<span style="color: #408080; font-style: italic"># Generate the data.</span>
nsamples <span style="color: #666666">=</span> <span style="color: #666666">100</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(nsamples)
y <span style="color: #666666">=</span> <span style="color: #666666">3*</span>x<span style="color: #666666">**2</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(nsamples)
<span style="color: #408080; font-style: italic">## Cross-validation on Ridge regression using KFold only</span>
<span style="color: #408080; font-style: italic"># Decide degree on polynomial to fit</span>
poly <span style="color: #666666">=</span> PolynomialFeatures(degree <span style="color: #666666">=</span> <span style="color: #666666">6</span>)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">500</span>
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-3</span>, <span style="color: #666666">5</span>, nlambdas)
<span style="color: #408080; font-style: italic"># Initialize a KFold instance</span>
k <span style="color: #666666">=</span> <span style="color: #666666">5</span>
kfold <span style="color: #666666">=</span> KFold(n_splits <span style="color: #666666">=</span> k)
<span style="color: #408080; font-style: italic"># Perform the cross-validation to estimate MSE</span>
scores_KFold <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((nlambdas, k))
i <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> lmb <span style="color: #AA22FF; font-weight: bold">in</span> lambdas:
ridge <span style="color: #666666">=</span> Ridge(alpha <span style="color: #666666">=</span> lmb)
j <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> train_inds, test_inds <span style="color: #AA22FF; font-weight: bold">in</span> kfold<span style="color: #666666">.</span>split(x):
xtrain <span style="color: #666666">=</span> x[train_inds]
ytrain <span style="color: #666666">=</span> y[train_inds]
xtest <span style="color: #666666">=</span> x[test_inds]
ytest <span style="color: #666666">=</span> y[test_inds]
Xtrain <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(xtrain[:, np<span style="color: #666666">.</span>newaxis])
ridge<span style="color: #666666">.</span>fit(Xtrain, ytrain[:, np<span style="color: #666666">.</span>newaxis])
Xtest <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(xtest[:, np<span style="color: #666666">.</span>newaxis])
ypred <span style="color: #666666">=</span> ridge<span style="color: #666666">.</span>predict(Xtest)
scores_KFold[i,j] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum((ypred <span style="color: #666666">-</span> ytest[:, np<span style="color: #666666">.</span>newaxis])<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(ypred)
j <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
i <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
estimated_mse_KFold <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(scores_KFold, axis <span style="color: #666666">=</span> <span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic">## Cross-validation using cross_val_score from sklearn along with KFold</span>
<span style="color: #408080; font-style: italic"># kfold is an instance initialized above as:</span>
<span style="color: #408080; font-style: italic"># kfold = KFold(n_splits = k)</span>
estimated_mse_sklearn <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
i <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> lmb <span style="color: #AA22FF; font-weight: bold">in</span> lambdas:
ridge <span style="color: #666666">=</span> Ridge(alpha <span style="color: #666666">=</span> lmb)
X <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(x[:, np<span style="color: #666666">.</span>newaxis])
estimated_mse_folds <span style="color: #666666">=</span> cross_val_score(ridge, X, y[:, np<span style="color: #666666">.</span>newaxis], scoring<span style="color: #666666">=</span><span style="color: #BA2121">&#39;neg_mean_squared_error&#39;</span>, cv<span style="color: #666666">=</span>kfold)
<span style="color: #408080; font-style: italic"># cross_val_score return an array containing the estimated negative mse for every fold.</span>
<span style="color: #408080; font-style: italic"># we have to the the mean of every array in order to get an estimate of the mse of the model</span>
estimated_mse_sklearn[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(<span style="color: #666666">-</span>estimated_mse_folds)
i <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
<span style="color: #408080; font-style: italic">## Plot and compare the slightly different ways to perform cross-validation</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), estimated_mse_sklearn, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;cross_val_score&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), estimated_mse_KFold, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;KFold&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;mse&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-examples-on-bootstrap-and-cross-validation-and-errors">More examples on bootstrap and cross-validation and errors </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression, Ridge, Lasso
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results&quot;</span>
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results/FigureFiles&quot;</span>
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;DataFiles/&quot;</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
os<span style="color: #666666">.</span>makedirs(DATA_ID)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;.png&quot;</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">&#39;png&#39;</span>)
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">&quot;EoS.csv&quot;</span>),<span style="color: #BA2121">&#39;r&#39;</span>)
<span style="color: #408080; font-style: italic"># Read the EoS data as csv file and organize the data into two arrays with density and energies</span>
EoS <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile, names<span style="color: #666666">=</span>(<span style="color: #BA2121">&#39;Density&#39;</span>, <span style="color: #BA2121">&#39;Energy&#39;</span>))
EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>] <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>to_numeric(EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>], errors<span style="color: #666666">=</span><span style="color: #BA2121">&#39;coerce&#39;</span>)
EoS <span style="color: #666666">=</span> EoS<span style="color: #666666">.</span>dropna()
Energies <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>]
Density <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">&#39;Density&#39;</span>]
<span style="color: #408080; font-style: italic"># The design matrix now as function of various polytrops</span>
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">30</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(Density),Maxpolydegree))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
testerror <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Maxpolydegree)
trainingerror <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Maxpolydegree)
polynomial <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Maxpolydegree)
trials <span style="color: #666666">=</span> <span style="color: #666666">100</span>
<span style="color: #008000; font-weight: bold">for</span> polydegree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>, Maxpolydegree):
polynomial[polydegree] <span style="color: #666666">=</span> polydegree
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(polydegree):
X[:,degree] <span style="color: #666666">=</span> Density<span style="color: #666666">**</span>(degree<span style="color: #666666">/3.0</span>)
<span style="color: #408080; font-style: italic"># loop over trials in order to estimate the expectation value of the MSE</span>
testerror[polydegree] <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
trainingerror[polydegree] <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #008000; font-weight: bold">for</span> samples <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(trials):
x_train, x_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, Energies, test_size<span style="color: #666666">=0.2</span>)
model <span style="color: #666666">=</span> LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)<span style="color: #666666">.</span>fit(x_train, y_train)
ypred <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(x_train)
ytilde <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(x_test)
testerror[polydegree] <span style="color: #666666">+=</span> mean_squared_error(y_test, ytilde)
trainingerror[polydegree] <span style="color: #666666">+=</span> mean_squared_error(y_train, ypred)
testerror[polydegree] <span style="color: #666666">/=</span> trials
trainingerror[polydegree] <span style="color: #666666">/=</span> trials
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Degree of polynomial: </span><span style="color: #BB6688; font-weight: bold">%3d</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span> polynomial[polydegree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Mean squared error on training data: </span><span style="color: #BB6688; font-weight: bold">%.8f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> trainingerror[polydegree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Mean squared error on test data: </span><span style="color: #BB6688; font-weight: bold">%.8f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> testerror[polydegree])
plt<span style="color: #666666">.</span>plot(polynomial, np<span style="color: #666666">.</span>log10(trainingerror), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Training Error&#39;</span>)
plt<span style="color: #666666">.</span>plot(polynomial, np<span style="color: #666666">.</span>log10(testerror), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Test Error&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Polynomial degree&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;log10[MSE]&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Note that we kept the intercept column in the fitting here. This means that we need to set the <b>intercept</b> in the call to the <b>Scikit-Learn</b> function as <b>False</b>. Alternatively, we could have set up the design matrix \( X \) without the first column of ones.</p>
<!-- !split -->
<h2 id="the-same-example-but-now-with-cross-validation">The same example but now with cross-validation </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>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression, Ridge, Lasso
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> KFold
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_val_score
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results&quot;</span>
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results/FigureFiles&quot;</span>
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;DataFiles/&quot;</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
os<span style="color: #666666">.</span>makedirs(DATA_ID)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;.png&quot;</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">&#39;png&#39;</span>)
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">&quot;EoS.csv&quot;</span>),<span style="color: #BA2121">&#39;r&#39;</span>)
<span style="color: #408080; font-style: italic"># Read the EoS data as csv file and organize the data into two arrays with density and energies</span>
EoS <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile, names<span style="color: #666666">=</span>(<span style="color: #BA2121">&#39;Density&#39;</span>, <span style="color: #BA2121">&#39;Energy&#39;</span>))
EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>] <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>to_numeric(EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>], errors<span style="color: #666666">=</span><span style="color: #BA2121">&#39;coerce&#39;</span>)
EoS <span style="color: #666666">=</span> EoS<span style="color: #666666">.</span>dropna()
Energies <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">&#39;Energy&#39;</span>]
Density <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">&#39;Density&#39;</span>]
<span style="color: #408080; font-style: italic"># The design matrix now as function of various polytrops</span>
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">30</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(Density),Maxpolydegree))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
estimated_mse_sklearn <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Maxpolydegree)
polynomial <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Maxpolydegree)
k <span style="color: #666666">=5</span>
kfold <span style="color: #666666">=</span> KFold(n_splits <span style="color: #666666">=</span> k)
<span style="color: #008000; font-weight: bold">for</span> polydegree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>, Maxpolydegree):
polynomial[polydegree] <span style="color: #666666">=</span> polydegree
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(polydegree):
X[:,degree] <span style="color: #666666">=</span> Density<span style="color: #666666">**</span>(degree<span style="color: #666666">/3.0</span>)
OLS <span style="color: #666666">=</span> LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
<span style="color: #408080; font-style: italic"># loop over trials in order to estimate the expectation value of the MSE</span>
estimated_mse_folds <span style="color: #666666">=</span> cross_val_score(OLS, X, Energies, scoring<span style="color: #666666">=</span><span style="color: #BA2121">&#39;neg_mean_squared_error&#39;</span>, cv<span style="color: #666666">=</span>kfold)
<span style="color: #408080; font-style: italic">#[:, np.newaxis]</span>
estimated_mse_sklearn[polydegree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(<span style="color: #666666">-</span>estimated_mse_folds)
plt<span style="color: #666666">.</span>plot(polynomial, np<span style="color: #666666">.</span>log10(estimated_mse_sklearn), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Test Error&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Polynomial degree&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;log10[MSE]&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="material-for-the-lab-sessions">Material for the lab sessions </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 href="https://www.youtube.com/watch?v=T9jjWsmsd1o" target="_blank"><tt>https://www.youtube.com/watch?v=T9jjWsmsd1o</tt></a></p>
<p>See also video on ADAgrad, RMSprop and ADAM (material from last week not covered during lecture) at <a href="https://youtu.be/J_41Hld6tTU" target="_blank"><tt>https://youtu.be/J_41Hld6tTU</tt></a></p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>