Files
FYS-STK4155/doc/pub/Regression/html/Regression.html
T
2018-10-11 05:27:04 +02:00

4098 lines
247 KiB
HTML

<!--
Automatically generated HTML file from DocOnce source
(https://github.com/hplgit/doconce/)
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
<meta name="description" content="Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis">
<title>Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis</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 { color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
/* pre style removed because it will interfer with pygments */
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}
.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/hplgit/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Regression analysis, overarching aims', 2, None, '___sec0'),
('Regression analysis, overarching aims II', 2, None, '___sec1'),
('General linear models', 2, None, '___sec2'),
('Rewriting the fitting procedure as a linear algebra problem',
2,
None,
'___sec3'),
('Rewriting the fitting procedure as a linear algebra problem, '
'follows',
2,
None,
'___sec4'),
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'___sec5'),
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'___sec6'),
('Optimizing our parameters', 2, None, '___sec7'),
('Optimizing our parameters, more details', 2, None, '___sec8'),
('Interpretations and optimizing our parameters',
2,
None,
'___sec9'),
('Interpretations and optimizing our parameters',
2,
None,
'___sec10'),
('Interpretations and optimizing our parameters',
2,
None,
'___sec11'),
('The $\\chi^2$ function', 2, None, '___sec12'),
('The $\\chi^2$ function', 2, None, '___sec13'),
('The $\\chi^2$ function', 2, None, '___sec14'),
('The $\\chi^2$ function', 2, None, '___sec15'),
('The $\\chi^2$ function', 2, None, '___sec16'),
('The $\\chi^2$ function', 2, None, '___sec17'),
('Simple regression model', 2, None, '___sec18'),
('Simple regression model, now using _scikit-learn_',
2,
None,
'___sec19'),
('Simple linear regression model using _scikit-learn_',
2,
None,
'___sec20'),
('Simple linear regression model', 2, None, '___sec21'),
('Less noise', 2, None, '___sec22'),
('How to study our fits', 2, None, '___sec23'),
('Minimizing the cost function', 2, None, '___sec24'),
('Relative error', 2, None, '___sec25'),
('The richness of _scikit-learn_', 2, None, '___sec26'),
('Functions in _scikit-learn_', 2, None, '___sec27'),
('Other functions in _scikit-learn_', 2, None, '___sec28'),
('The mean absolute error and other functions in _scikit-learn_',
2,
None,
'___sec29'),
('Cubic polynomial in _scikit-learn_', 2, None, '___sec30'),
('Polynomial Regression', 2, None, '___sec31'),
('Linking the regression analysis with a statistical '
'interpretation',
2,
None,
'___sec32'),
('Expectation value and variance', 2, None, '___sec33'),
('The singular value decompostion', 2, None, '___sec34'),
('From standard regression to Ridge regressions',
2,
None,
'___sec35'),
('Fixing the singularity', 2, None, '___sec36'),
('Fitting vs. predicting when data is in the model class',
2,
None,
'___sec37'),
('Fitting versus predicting when data is not in the model class',
2,
None,
'___sec38'),
('An example code without the model assessment part',
2,
None,
'___sec39'),
('Generating test data', 2, None, '___sec40'),
('How can we effectively evaluate the various models?',
2,
None,
'___sec41'),
('Code examples for Ridge and Lasso Regression',
2,
None,
'___sec42'),
('A second-order polynomial with Ridge and Lasso',
2,
None,
'___sec43'),
('Resampling methods', 2, None, '___sec44'),
('Resampling approaches can be computationally expensive',
2,
None,
'___sec45'),
('Why resampling methods ?', 2, None, '___sec46'),
('Statistical analysis', 2, None, '___sec47'),
('Statistics', 2, None, '___sec48'),
('Statistics, moments', 2, None, '___sec49'),
('Statistics, central moments', 2, None, '___sec50'),
('Statistics, covariance', 2, None, '___sec51'),
('Statistics, more covariance', 2, None, '___sec52'),
('Statistics, independent variables', 2, None, '___sec53'),
('Statistics, more variance', 2, None, '___sec54'),
('Statistics and stochastic processes', 2, None, '___sec55'),
('Statistics and sample variables', 2, None, '___sec56'),
('Statistics, sample variance and covariance',
2,
None,
'___sec57'),
('Statistics, law of large numbers', 2, None, '___sec58'),
('Statistics, more on sample error', 2, None, '___sec59'),
('Statistics', 2, None, '___sec60'),
('Statistics, central limit theorem', 2, None, '___sec61'),
('Statistics, more technicalities', 2, None, '___sec62'),
('Statistics', 2, None, '___sec63'),
('Statistics and sample variance', 2, None, '___sec64'),
('Statistics, uncorrelated results', 2, None, '___sec65'),
('Statistics, computations', 2, None, '___sec66'),
('Statistics, more on computations of errors',
2,
None,
'___sec67'),
('Statistics, wrapping up 1', 2, None, '___sec68'),
('Statistics, final expression', 2, None, '___sec69'),
('Statistics, effective number of correlations',
2,
None,
'___sec70'),
('Log-likelihood', 2, None, '___sec71'),
('Cross-validation', 2, None, '___sec72'),
('Computationally expensive', 2, None, '___sec73'),
('Various steps in cross-validation', 2, None, '___sec74'),
('How to set up the cross-validation for Ridge and/or Lasso',
2,
None,
'___sec75'),
('Predicted Residual Error Sum of Squares', 2, None, '___sec76'),
('Resampling methods: Jackknife and Bootstrap',
2,
None,
'___sec77'),
('Resampling methods: Jackknife', 2, None, '___sec78'),
('Resampling methods: Jackknife estimator', 2, None, '___sec79'),
('Jackknife code example', 2, None, '___sec80'),
('Resampling methods: Bootstrap', 2, None, '___sec81'),
('Resampling methods: Bootstrap background', 2, None, '___sec82'),
('Resampling methods: More Bootstrap background',
2,
None,
'___sec83'),
('Resampling methods: Bootstrap approach', 2, None, '___sec84'),
('Resampling methods: Bootstrap steps', 2, None, '___sec85'),
('Code example for the Bootstrap method', 2, None, '___sec86'),
('Resampling methods: Blocking', 2, None, '___sec87'),
('Blocking Transformations', 2, None, '___sec88'),
('Blocking Transformations', 2, None, '___sec89'),
('Blocking Transformations, getting there', 2, None, '___sec90'),
('Blocking Transformations, final expressions',
2,
None,
'___sec91'),
('"Code examples for Blocking, Jackknife and '
'bootstrap":"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts"',
2,
None,
'___sec92'),
('The bias-variance tradeoff', 2, None, '___sec93'),
('Training and testing data', 2, None, '___sec94'),
('Procedure to find a predictor', 2, None, '___sec95'),
('What we want', 2, None, '___sec96'),
('The expected generalization error', 2, None, '___sec97'),
('Elaborating a little bit more', 2, None, '___sec98'),
('The bias', 2, None, '___sec99'),
('The variance', 2, None, '___sec100'),
('Summing up', 2, None, '___sec101'),
('The one-dimensional Ising model, project 2',
2,
None,
'___sec102'),
('Example: The one-dimensional Ising model',
2,
None,
'___sec103'),
('Reformulating the problem to suit regression',
2,
None,
'___sec104'),
('Linear regression', 2, None, '___sec105'),
('Ordinary least squares', 2, None, '___sec106'),
('Singular Value decomposition', 2, None, '___sec107'),
('Fitting with scikit-learn', 2, None, '___sec108'),
('Ridge regression', 2, None, '___sec109'),
('LASSO regression', 2, None, '___sec110'),
('Performance of the different models', 2, None, '___sec111'),
('Performance as function of the regularization parameter',
2,
None,
'___sec112'),
('Finding the optimal value of $\\lambda$',
2,
None,
'___sec113')]}
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>Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>
<!-- institution(s) -->
<center>[1] <b>Department of Physics, University of Oslo</b></center>
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Oct 11, 2018</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec0">Regression analysis, overarching aims </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \).
The first variable is called the <b>dependent</b>, the <b>outcome</b> or the <b>response</b> variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
<p>
A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with
<ul>
<li> \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)</li>
<li> Response (dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)</li>
<li> \( p \) Explanatory (independent or predictor) variables \( \hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}] \) with \( i = 0, 1, 2, \dots, n-1 \)</li>
</ul>
The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec1">Regression analysis, overarching aims II </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
Consider an experiment in which \( p \) characteristics of \( n \) samples are
measured. The data from this experiment are denoted \( \mathbf{X} \), with
\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the <em>design
matrix</em>. Additional information of the samples is available in the
form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is
generally referred to as the <em>response variable</em>. The aim of
regression analysis is to explain \( \mathbf{Y} \) in terms of
\( \mathbf{X} \) through a functional relationship like \( Y_i =
f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of
\( f(\cdot) \) is available, it is common to assume a linear relationship
between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to
the <em>linear regression model</em> where \( \beta = (\beta_1, \ldots,
\beta_p)^{\top} \) is the <em>regression parameter</em>. The parameter
\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate
\( j \) on the response. That is, for each unit change in covariate \( j \)
(while keeping the other covariates fixed) the observed change in the
response is equal to \( \beta_j \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec2">General linear models </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
<p>
Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is
$$
y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i,
$$
where \( \epsilon_i \) is the error in our approximation.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec3">Rewriting the fitting procedure as a linear algebra problem </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
For every set of values \( y_i,x_i \) we have thus the corresponding set of equations
$$
\begin{align*}
y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\
y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\
y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\
\dots & \dots \\
y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec4">Rewriting the fitting procedure as a linear algebra problem, follows </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Defining the vectors
$$
\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
$$
and
$$
\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
$$
and
$$
\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
$$
and the matrix
$$
\hat{X}=
\begin{bmatrix}
1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\
1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\
1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\
\dots& \dots &\dots& \dots & \dots &\dots\\
1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\
\end{bmatrix}
$$
we can rewrite our equations as
$$
\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec5">Generalizing the fitting procedure as a linear algebra problem </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions.
For every set of values \( y_i,x_i \) we can then generalize the equations to
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\
y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\
\dots & \dots \\
y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec6">Generalizing the fitting procedure as a linear algebra problem </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We redefine in turn the matrix \( \hat{X} \) as
$$
\hat{X}=
\begin{bmatrix}
x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\
x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\
x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\
\dots& \dots &\dots& \dots & \dots &\dots\\
x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\
\end{bmatrix}
$$
and without loss of generality we rewrite again our equations as
$$
\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
$$
The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec7">Optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We have defined the matrix \( \hat{X} \)
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\
y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\
\dots & \dots \\
y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec8">Optimizing our parameters, more details </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as
$$
\hat{\tilde{y}}= \hat{X}\hat{\beta},
$$
and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely
$$
Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right),
$$
or using the matrix \( \hat{X} \) as
$$
Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right).
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec9">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The function
$$
Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right),
$$
can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value
$$
y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i,
$$
where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable.
<p>
In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring
$$
\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
$$
which results in
$$
\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
$$
or in a matrix-vector form as
$$
\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right).
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec10">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We can rewrite
$$
\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right),
$$
as
$$
\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta},
$$
and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution
$$
\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}.
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec11">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The residuals \( \hat{\epsilon} \) are in turn given by
$$
\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta},
$$
and with
$$
\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
$$
we have
$$
\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
$$
meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec12">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable.
<p>
Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as
$$
\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right),
$$
where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec13">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0,
$$
which results in
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0,
$$
or in a matrix-vector form as
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right).
$$
where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec14">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
We can rewrite
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right),
$$
as
$$
\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta},
$$
and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution
$$
\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}.
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec15">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
If we then introduce the matrix
$$
\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1},
$$
we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \))
$$
\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik}
$$
We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)
$$
\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2,
$$
resulting in
$$
\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}!
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec16">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write
$$
y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i.
$$
By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
$$
and
$$
\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec17">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
For a linear fit we don't need to invert a matrix!!
Defining
$$
\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2},
$$
$$
\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2},
$$
$$
\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right),
$$
$$
\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2},
$$
$$
\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2},
$$
we obtain
$$
\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2},
$$
$$
\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}.
$$
<p>
This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec18">Simple regression model </h2>
We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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">print</span>(np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>array([<span style="color: #666666">1</span>,<span style="color: #666666">2</span>,<span style="color: #666666">3</span>]), np<span style="color: #666666">.</span>array([<span style="color: #666666">4</span>,<span style="color: #666666">5</span>,<span style="color: #666666">6</span>])])
<span style="color: #008000; font-weight: bold">print</span>(np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>array([[<span style="color: #666666">1</span>,<span style="color: #666666">2</span>,<span style="color: #666666">3</span>]]), <span style="color: #666666">0</span>, <span style="color: #666666">0</span>, np<span style="color: #666666">.</span>array([[<span style="color: #666666">4</span>,<span style="color: #666666">5</span>,<span style="color: #666666">6</span>]])])
</pre></div>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
<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>
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
xb <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)), x]
beta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb))<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>T)<span style="color: #666666">.</span>dot(y)
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
xbnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)), xnew]
ypredict <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(beta)
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Linear Regression&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec19">Simple regression model, now using <b>scikit-learn</b> </h2>
<p>
We can repeat the above algorithm using <b>scikit-learn</b> as follows
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
<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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
linreg <span style="color: #666666">=</span> LinearRegression()
linreg<span style="color: #666666">.</span>fit(x,y)
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(xnew)
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Random numbers &#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec20">Simple linear regression model using <b>scikit-learn</b> </h2>
<p>
We start with perhaps our simplest possible example, using <b>scikit-learn</b> to perform linear regression analysis on a data set produced by us.
What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution.
<p>
The Numpy functions are imported used the <b>import numpy as np</b>
statement and the random number generator for the uniform distribution
is called using the function <b>np.random.rand()</b>, where we specificy
that we want \( 100 \) random variables. Using Numpy we define
automatically an array with the specified number of elements, \( 100 \) in
our case. With the Numpy function <b>randn()</b> we can compute random
numbers with the normal distribution (mean value \( \mu \) equal to zero and
variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear
dependence as function of \( x \)
$$
y = 2x+N(0,1),
$$
<p>
where \( N(0,1) \) represents random numbers generated by the normal
distribution. From <b>scikit-learn</b> we import then the
<b>LinearRegression</b> functionality and make a prediction \( \tilde{y} =
\alpha + \beta x \) using the function <b>fit(x,y)</b>. We call the set of
data \( (\hat{x},\hat{y}) \) for our training data. The Python package
<b>scikit-learn</b> has also a functionality which extracts the above
fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will
distinguish between training data and test data.
<p>
For plotting we use the Python package
<a href="https://matplotlib.org/" target="_blank">matplotlib</a> which produces publication
quality figures. Feel free to explore the extensive
<a href="https://matplotlib.org/gallery/index.html" target="_blank">gallery</a> of examples. In
this example we plot our original values of \( x \) and \( y \) as well as the
prediction <b>ypredict</b> (\( \tilde{y} \)), which attempts at fitting our
data with a straight line.
<p>
The Python code follows here.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
linreg <span style="color: #666666">=</span> LinearRegression()
linreg<span style="color: #666666">.</span>fit(x,y)
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">1</span>]])
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(xnew)
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">5.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Simple Linear Regression&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec21">Simple linear regression model </h2>
<p>
This example serves several aims. It allows us to demonstrate several
aspects of data analysis and later machine learning algorithms. The
immediate visualization shows that our linear fit is not
impressive. It goes through the data points, but there are many
outliers which are not reproduced by our linear regression. We could
now play around with this small program and change for example the
factor in front of \( x \) and the normal distribution. Try to change the
function \( y \) to
$$
y = 10x+0.01 \times N(0,1),
$$
<p>
where \( x \) is defined as before.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec22">Less noise </h2>
<p>
Does the fit look better? Indeed, by
reducing the role of the normal distribution we see immediately that
our linear prediction seemingly reproduces better the training
set. However, this testing 'by the eye' is obviouly not satisfactory in the
long run. Here we have only defined the training data and our model, and
have not discussed a more rigorous approach to the <b>cost</b> function.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec23">How to study our fits </h2>
<p>
We need more rigorous criteria in defining whether we have succeeded or
not in modeling our training data. You will be surprised to see that
many scientists seldomly venture beyond this 'by the eye' approach. A
standard approach for the <em>cost</em> function is the so-called \( \chi^2 \)
function
$$ \chi^2 = \frac{1}{n}
\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2},
$$
<p>
where \( \sigma_i^2 \) is the variance (to be defined later) of the entry
\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves
however the aim of scaling the equations and make the cost function
dimensionless.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec24">Minimizing the cost function </h2>
<p>
Minimizing the cost function is a central aspect of
our discussions to come. Finding its minima as function of the model
parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring
theme in these series of lectures. Essentially all machine learning
algorithms we will discuss center around the minimization of the
chosen cost function. This depends in turn on our specific
model for describing the data, a typical situation in supervised
learning. Automatizing the search for the minima of the cost function is a
central ingredient in all algorithms. Typical methods which are
employed are various variants of <b>gradient</b> methods. These will be
discussed in more detail later. Again, you'll be surprised to hear that
many practitioners minimize the above function ''by the eye', popularly dubbed as
'chi by the eye'. That is, change a parameter and see (visually and numerically) that
the \( \chi^2 \) function becomes smaller.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec25">Relative error </h2>
<p>
There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define
the relative error as
$$
\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}.
$$
We can modify easily the above Python code and plot the relative error instead
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">5*</span>x<span style="color: #666666">+0.01*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
linreg <span style="color: #666666">=</span> LinearRegression()
linreg<span style="color: #666666">.</span>fit(x,y)
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(x)
plt<span style="color: #666666">.</span>plot(x, np<span style="color: #666666">.</span>abs(ypredict<span style="color: #666666">-</span>y)<span style="color: #666666">/</span><span style="color: #008000">abs</span>(y), <span style="color: #BA2121">&quot;ro&quot;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">0.0</span>, <span style="color: #666666">0.5</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$\epsilon_{\mathrm{relative}}$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Relative error&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
Depending on the parameter in front of the normal distribution, we may
have a small or larger relative error. Try to play around with
different training data sets and study (graphically) the value of the
relative error.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec26">The richness of <b>scikit-learn</b> </h2>
<p>
As mentioned above, <b>scikit-learn</b> has an impressive functionality.
We can for example extract the values of \( \alpha \) and \( \beta \) and
their error estimates, or the variance and standard deviation and many
other properties from the statistical data analysis.
<p>
Here we show an
example of the functionality of scikit-learn.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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.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.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+</span> <span style="color: #666666">5*</span>x<span style="color: #666666">+0.5*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
linreg <span style="color: #666666">=</span> LinearRegression()
linreg<span style="color: #666666">.</span>fit(x,y)
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(x)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;The intercept alpha: </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, linreg<span style="color: #666666">.</span>intercept_)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Coefficient beta : </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, linreg<span style="color: #666666">.</span>coef_)
<span style="color: #408080; font-style: italic"># The mean squared error </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Mean squared error: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> mean_squared_error(y, ypredict))
<span style="color: #408080; font-style: italic"># Explained variance score: 1 is perfect prediction </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Variance score: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> r2_score(y, ypredict))
<span style="color: #408080; font-style: italic"># Mean squared log error </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Mean squared log error: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> mean_squared_log_error(y, ypredict) )
<span style="color: #408080; font-style: italic"># Mean absolute error </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Mean absolute error: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> mean_absolute_error(y, ypredict))
plt<span style="color: #666666">.</span>plot(x, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0.0</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">1.5</span>, <span style="color: #666666">7.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Linear Regression fit &#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec27">Functions in <b>scikit-learn</b> </h2>
<p>
The function <b>coef</b> gives us the parameter \( \beta \) of our fit while <b>intercept</b> yields
\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function <b>meansquarederror</b> gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as
$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
$$
<p>
The smaller the value, the better the fit. Ideally we would like to
have an MSE equal zero. The attentive reader has probably recognized
this function as being similar to the \( \chi^2 \) function defined above.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec28">Other functions in <b>scikit-learn</b> </h2>
<p>
The <b>r2score</b> function computes \( R^2 \), the coefficient of
determination. It provides a measure of how well future samples are
likely to be predicted by the model. Best possible score is 1.0 and it
can be negative (because the model can be arbitrarily worse). A
constant model that always predicts the expected value of \( \hat{y} \),
disregarding the input features, would get a \( R^2 \) score of \( 0.0 \).
<p>
If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
$$
R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
$$
where we have defined the mean value of \( \hat{y} \) as
$$
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec29">The mean absolute error and other functions in <b>scikit-learn</b> </h2>
<p>
Another quantity will meet again in our discussions of regression analysis is
mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error.
The MAE is defined as follows
$$
\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|.
$$
Finally we present the
squared logarithmic (quadratic) error
$$
\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2,
$$
<p>
where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error
estimate is best to use when targets having exponential growth, such
as population counts, average sales of a commodity over a span of
years etc.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec30">Cubic polynomial in <b>scikit-learn</b> </h2>
<p>
We will discuss in more
detail these and other functions in the various lectures. We conclude this part with another example. Instead of
a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn.
Add description of the various python commands.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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">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">random</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> Ridge
<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.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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
x<span style="color: #666666">=</span>np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0.02</span>,<span style="color: #666666">0.98</span>,<span style="color: #666666">200</span>)
noise <span style="color: #666666">=</span> np<span style="color: #666666">.</span>asarray(random<span style="color: #666666">.</span>sample((<span style="color: #008000">range</span>(<span style="color: #666666">200</span>)),<span style="color: #666666">200</span>))
y<span style="color: #666666">=</span>x<span style="color: #666666">**3*</span>noise
yn<span style="color: #666666">=</span>x<span style="color: #666666">**3*100</span>
poly3 <span style="color: #666666">=</span> PolynomialFeatures(degree<span style="color: #666666">=3</span>)
X <span style="color: #666666">=</span> poly3<span style="color: #666666">.</span>fit_transform(x[:,np<span style="color: #666666">.</span>newaxis])
clf3 <span style="color: #666666">=</span> LinearRegression()
clf3<span style="color: #666666">.</span>fit(X,y)
Xplot<span style="color: #666666">=</span>poly3<span style="color: #666666">.</span>fit_transform(x[:,np<span style="color: #666666">.</span>newaxis])
poly3_plot<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x, clf3<span style="color: #666666">.</span>predict(Xplot), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Cubic Fit&#39;</span>)
plt<span style="color: #666666">.</span>plot(x,yn, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;red&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;True Cubic&quot;</span>)
plt<span style="color: #666666">.</span>scatter(x, y, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Data&#39;</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;orange&#39;</span>, s<span style="color: #666666">=15</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">error</span>(a):
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> y:
err<span style="color: #666666">=</span>(y<span style="color: #666666">-</span>yn)<span style="color: #666666">/</span>yn
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">abs</span>(np<span style="color: #666666">.</span>sum(err))<span style="color: #666666">/</span><span style="color: #008000">len</span>(err)
<span style="color: #008000; font-weight: bold">print</span> (error(y))
</pre></div>
<p>
Using <b>R</b>, we can perform similar studies.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec31">Polynomial Regression </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">math</span> <span style="color: #008000; font-weight: bold">import</span> exp, sqrt
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
<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>
m <span style="color: #666666">=</span> <span style="color: #666666">100</span>
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(m,<span style="color: #666666">1</span>)<span style="color: #666666">+4.</span>
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+</span> <span style="color: #666666">+</span>x<span style="color: #666666">-</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(m,<span style="color: #666666">1</span>)
xb <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((m,<span style="color: #666666">1</span>)), x]
theta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb))<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>T)<span style="color: #666666">.</span>dot(y)
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
xbnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)), xnew]
ypredict <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(theta)
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Random numbers &#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split -->
<h2 id="___sec32">Linking the regression analysis with a statistical interpretation </h2>
<p>
Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way.
<p>
It is assumed that \( \varepsilon_i
\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
independent, i.e.:
$$
\begin{align*}
\mbox{Cov}(\varepsilon_{i_1},
\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
\end{align*}
$$
The randomness of \( \varepsilon_i \) implies that
\( \mathbf{Y}_i \) is also a random variable. In particular,
\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim
\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec33">Expectation value and variance </h2>
<p>
Its expectation equals:
$$
\begin{align*}
\mathbb{E}(Y_i) & =
\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i)
\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
\end{align*}
$$
while
its variance is
$$
\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i
- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) -
[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ &
= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i
\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2
\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta +
\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2
\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
$$
Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec34">The singular value decompostion </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
A general
\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal
matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal
matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality
\( m \times m \) and the last dimensionality \( n\times n \).
We have then
$$
\hat{A} = \hat{U}\hat{D}\hat{V}^T
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec35">From standard regression to Ridge regressions </h2>
<p>
One of the typical problems we encounter with linear regression, in particular
when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional,
are problems with near singular or singular matrices. The column vectors of \( \hat{X} \)
may be linearly dependent, normally referred to as super-collinearity.
This means that the matrix may be rank deficient and it is basically impossible to
to model the data using linear regression. As an example, consider the matrix
$$
\begin{align*}
\mathbf{X} & = \left[
\begin{array}{rrr}
1 & -1 & 2
\\
1 & 0 & 1
\\
1 & 2 & -1
\\
1 & 1 & 0
\end{array} \right]
\end{align*}
$$
<p>
The columns of \( \hat{X} \) are linearly dependent. We se this easily since the
the first column is the row-wise sum of the other two columns. The rank (more correct,
the column rank) of a matrix is the dimension of the space spanned by the
column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number
of linearly independent columns. In this particular case the matrix has rank 2.
<p>
Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies
that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
$$
\begin{align*}
\hat{X} & = \left[
\begin{array}{rr}
1 & -1
\\
1 & -1
\end{array} \right].
\end{align*}
$$
We see easily that \( \mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigenvalue which is zero.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec36">Fixing the singularity </h2>
<p>
If our design matrix \( \hat{X} \) which enters the linear regression problem
$$
\begin{align}
\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y},
\label{_auto1}
\end{align}
$$
has linearly dependent column vectors, we will not be able to compute the inverse
of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits.
This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where
the regression parameters \( \beta_i \) cannot be estimated.
<p>
The <em>ad hoc</em> approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change
$$
\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I},
$$
where \( \hat{I} \) is the identity matrix.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec37">Fitting vs. predicting when data is in the model class </h2>
<p>
We start by considering the case
\( f(x)=2x \).
<p>
Then the data is clearly generated by a model that is contained within
all three model classes we are using to make predictions (linear
models, third order polynomials, and tenth order polynomials).
<p>
Run the code for the following cases:
<ol>
<li> For \( f(x)=2x \) , \( Ntrain=10 \) and \( \sigma =0 \) (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when \( x \in [0,1] \) . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?</li>
<li> Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?</li>
<li> Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example \( x \in [0,1.2] \) ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?</li>
<li> Repeat the above for \( f(x)=2x \) , \( Ntrain=10 \) , and \( \sigma=1 \) . What changes?</li>
</ol>
Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes?
Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec38">Fitting versus predicting when data is not in the model class </h2>
<p>
Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class.
<ol>
<li> Do better fits lead to better predictions?</li>
<li> What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points \( Ntrain \) and \( \sigma \)?</li>
</ol>
Summarize what you think you learned about the relationship of knowing the true model class and predictive power.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec39">An example code without the model assessment part </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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">sklearn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sk</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets, linear_model
<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">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">mpl</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
<span style="color: #666666">%</span>matplotlib notebook
<span style="color: #408080; font-style: italic"># The Training Data</span>
N_train<span style="color: #666666">=100</span>
sigma_train<span style="color: #666666">=1</span>;
<span style="color: #408080; font-style: italic"># Train on integers</span>
x<span style="color: #666666">=</span>np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0.05</span>,<span style="color: #666666">0.95</span>,N_train)
<span style="color: #408080; font-style: italic"># Draw random noise</span>
s <span style="color: #666666">=</span> sigma_train<span style="color: #666666">*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(N_train)
<span style="color: #408080; font-style: italic">#linear</span>
y<span style="color: #666666">=2*</span>x<span style="color: #666666">+</span>s
<span style="color: #408080; font-style: italic">#Tenth Order</span>
<span style="color: #408080; font-style: italic">#y=2*x-10*x**5+15*x**10+s</span>
p1<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x,y, <span style="color: #BA2121">&quot;o&quot;</span>,ms<span style="color: #666666">=15</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Training&#39;</span>)
<span style="color: #408080; font-style: italic">#Linear Regression</span>
<span style="color: #408080; font-style: italic"># Create linear regression object</span>
clf <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>LinearRegression()
<span style="color: #408080; font-style: italic"># Train the model using the training sets</span>
clf<span style="color: #666666">.</span>fit(x[:, np<span style="color: #666666">.</span>newaxis], y)
<span style="color: #408080; font-style: italic"># The coefficients</span>
xplot<span style="color: #666666">=</span>np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0.02</span>,<span style="color: #666666">0.98</span>,<span style="color: #666666">200</span>)
linear_plot<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(xplot, clf<span style="color: #666666">.</span>predict(xplot[:, np<span style="color: #666666">.</span>newaxis]),label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Linear&#39;</span>)
<span style="color: #408080; font-style: italic">#Polynomial Regression</span>
poly3 <span style="color: #666666">=</span> PolynomialFeatures(degree<span style="color: #666666">=3</span>)
X <span style="color: #666666">=</span> poly3<span style="color: #666666">.</span>fit_transform(x[:,np<span style="color: #666666">.</span>newaxis])
clf3 <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>LinearRegression()
clf3<span style="color: #666666">.</span>fit(X,y)
Xplot<span style="color: #666666">=</span>poly3<span style="color: #666666">.</span>fit_transform(xplot[:,np<span style="color: #666666">.</span>newaxis])
poly3_plot<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(xplot, clf3<span style="color: #666666">.</span>predict(Xplot), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Poly 3&#39;</span>)
<span style="color: #408080; font-style: italic">#poly5 = PolynomialFeatures(degree=5)</span>
<span style="color: #408080; font-style: italic">#X = poly5.fit_transform(x[:,np.newaxis])</span>
<span style="color: #408080; font-style: italic">#clf5 = linear_model.LinearRegression()</span>
<span style="color: #408080; font-style: italic">#clf5.fit(X,y)</span>
<span style="color: #408080; font-style: italic">#Xplot=poly5.fit_transform(xplot[:,np.newaxis])</span>
<span style="color: #408080; font-style: italic">#plt.plot(xplot, clf5.predict(Xplot), &#39;r--&#39;,linewidth=1)</span>
poly10 <span style="color: #666666">=</span> PolynomialFeatures(degree<span style="color: #666666">=10</span>)
X <span style="color: #666666">=</span> poly10<span style="color: #666666">.</span>fit_transform(x[:,np<span style="color: #666666">.</span>newaxis])
clf10 <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>LinearRegression()
clf10<span style="color: #666666">.</span>fit(X,y)
Xplot<span style="color: #666666">=</span>poly10<span style="color: #666666">.</span>fit_transform(xplot[:,np<span style="color: #666666">.</span>newaxis])
poly10_plot<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(xplot, clf10<span style="color: #666666">.</span>predict(Xplot), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Poly 10&#39;</span>)
axes <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>gca()
axes<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-7</span>,<span style="color: #666666">7</span>])
handles, labels<span style="color: #666666">=</span>axes<span style="color: #666666">.</span>get_legend_handles_labels()
plt<span style="color: #666666">.</span>legend(handles,labels, loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;lower center&#39;</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>)
Title<span style="color: #666666">=</span><span style="color: #BA2121">&quot;$N=$&quot;</span><span style="color: #666666">+</span><span style="color: #008000">str</span>(N_train)<span style="color: #666666">+</span><span style="color: #BA2121">&quot;, $\sigma=$&quot;</span><span style="color: #666666">+</span><span style="color: #008000">str</span>(sigma_train)
plt<span style="color: #666666">.</span>title(Title<span style="color: #666666">+</span><span style="color: #BA2121">&quot; (train)&quot;</span>)
plt<span style="color: #666666">.</span>tight_layout()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split -->
<h2 id="___sec40">Generating test data </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Generate Test Data</span>
<span style="color: #408080; font-style: italic">#Number of test data</span>
N_test<span style="color: #666666">=20</span>
sigma_test<span style="color: #666666">=</span>sigma_train
max_x<span style="color: #666666">=1.2</span>
x_test<span style="color: #666666">=</span>max_x<span style="color: #666666">*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>random(N_test)
<span style="color: #408080; font-style: italic"># Draw random noise</span>
s_test <span style="color: #666666">=</span> sigma_test<span style="color: #666666">*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(N_test)
<span style="color: #408080; font-style: italic">#Linear</span>
y_test<span style="color: #666666">=2*</span>x_test<span style="color: #666666">+</span>s_test
<span style="color: #408080; font-style: italic">#Tenth order</span>
<span style="color: #408080; font-style: italic">#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test</span>
<span style="color: #408080; font-style: italic">#Make design matrices for prediction</span>
x_plot<span style="color: #666666">=</span>np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,max_x, <span style="color: #666666">200</span>)
X3 <span style="color: #666666">=</span> poly3<span style="color: #666666">.</span>fit_transform(x_plot[:,np<span style="color: #666666">.</span>newaxis])
X10 <span style="color: #666666">=</span> poly10<span style="color: #666666">.</span>fit_transform(x_plot[:,np<span style="color: #666666">.</span>newaxis])
<span style="color: #666666">%</span>matplotlib notebook
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
p1<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x_test,y_test<span style="color: #666666">.</span>transpose(), <span style="color: #BA2121">&#39;o&#39;</span>, ms<span style="color: #666666">=12</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;data&#39;</span>)
p2<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x_plot,clf<span style="color: #666666">.</span>predict(x_plot[:,np<span style="color: #666666">.</span>newaxis]), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;linear&#39;</span>)
p3<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x_plot,clf3<span style="color: #666666">.</span>predict(X3), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;3rd order&#39;</span>)
p10<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>plot(x_plot,clf10<span style="color: #666666">.</span>predict(X10), label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;10th order&#39;</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=2</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;$y$&#39;</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;best&#39;</span>)
plt<span style="color: #666666">.</span>title(Title<span style="color: #666666">+</span><span style="color: #BA2121">&quot; (pred.)&quot;</span>)
plt<span style="color: #666666">.</span>tight_layout()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec41">How can we effectively evaluate the various models? </h2>
<p>
In Ridge regression and the subsequent discussion of its properties
the bias or penalty parameter is considered known or `given'. In
practice, it is unknown and the user needs to make an informed
decision on its value. How do we do that? Much of the same considerations apply to the Lasso method.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec42">Code examples for Ridge and Lasso Regression </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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">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</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
<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.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error, r2_score
<span style="color: #408080; font-style: italic">#creating data with random noise</span>
x<span style="color: #666666">=</span>np<span style="color: #666666">.</span>arange(<span style="color: #666666">50</span>)
delta<span style="color: #666666">=</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>uniform(<span style="color: #666666">-2.5</span>,<span style="color: #666666">2.5</span>, size<span style="color: #666666">=</span>(<span style="color: #666666">50</span>))
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>shuffle(delta)
y <span style="color: #666666">=0.5*</span>x<span style="color: #666666">+5+</span>delta
<span style="color: #408080; font-style: italic">#arranging data into 2x50 matrix</span>
a<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array(x) <span style="color: #408080; font-style: italic">#inputs</span>
b<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array(y) <span style="color: #408080; font-style: italic">#outputs</span>
<span style="color: #408080; font-style: italic">#Split into training and test</span>
X_train<span style="color: #666666">=</span>a[:<span style="color: #666666">37</span>, np<span style="color: #666666">.</span>newaxis]
X_test<span style="color: #666666">=</span>a[<span style="color: #666666">37</span>:, np<span style="color: #666666">.</span>newaxis]
y_train<span style="color: #666666">=</span>b[:<span style="color: #666666">37</span>]
y_test<span style="color: #666666">=</span>b[<span style="color: #666666">37</span>:]
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;X_train: &quot;</span>, X_train<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;y_train: &quot;</span>, y_train<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;X_test: &quot;</span>, X_test<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;y_test: &quot;</span>, y_test<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;------------------------------------&quot;</span>)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Ordinary Least Squares&quot;</span>)
<span style="color: #408080; font-style: italic">#Add Ordinary Least Squares fit</span>
reg<span style="color: #666666">=</span>LinearRegression()
reg<span style="color: #666666">.</span>fit(X_train, y_train)
pred<span style="color: #666666">=</span>reg<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Prediction Shape: &quot;</span>, pred<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Coefficients: </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, reg<span style="color: #666666">.</span>coef_)
<span style="color: #408080; font-style: italic"># The mean squared error</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Mean squared error: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&quot;</span>
<span style="color: #666666">%</span> mean_squared_error(y_test, pred))
<span style="color: #408080; font-style: italic"># Explained variance score: 1 is perfect prediction</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Variance score: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> r2_score(y_test, pred))
<span style="color: #408080; font-style: italic">#plot</span>
plt<span style="color: #666666">.</span>scatter(X_test,y_test,color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;green&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Training Data&quot;</span>)
plt<span style="color: #666666">.</span>plot(X_test, pred, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Fit Line&quot;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;------------------------------------&quot;</span>)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Ridge Regression&quot;</span>)
ridge<span style="color: #666666">=</span>linear_model<span style="color: #666666">.</span>RidgeCV(alphas<span style="color: #666666">=</span>[<span style="color: #666666">0.1</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">10.0</span>])
ridge<span style="color: #666666">.</span>fit(X_train,y_train)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Ridge Coefficient: &quot;</span>,ridge<span style="color: #666666">.</span>coef_)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Ridge Intercept: &quot;</span>, ridge<span style="color: #666666">.</span>intercept_)
<span style="color: #408080; font-style: italic">#Look into graphing with Ridge fit</span>
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;------------------------------------&quot;</span>)
<span style="color: #008000; font-weight: bold">print</span> (<span style="color: #BA2121">&quot;Lasso&quot;</span>)
lasso<span style="color: #666666">=</span>linear_model<span style="color: #666666">.</span>Lasso(alpha<span style="color: #666666">=0.1</span>)
lasso<span style="color: #666666">.</span>fit(X_train,y_train)
predl<span style="color: #666666">=</span>lasso<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Lasso Coefficient: &quot;</span>, lasso<span style="color: #666666">.</span>coef_)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Lasso Intercept: &quot;</span>, lasso<span style="color: #666666">.</span>intercept_)
plt<span style="color: #666666">.</span>scatter(X_test,y_test,color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;green&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Training Data&quot;</span>)
plt<span style="color: #666666">.</span>plot(X_test, predl, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;blue&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Lasso&quot;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec43">A second-order polynomial with Ridge and Lasso </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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.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.metrics</span> <span style="color: #008000; font-weight: bold">import</span> r2_score
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
n_samples <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>rand(n_samples,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">5*</span>x<span style="color: #666666">*</span>x <span style="color: #666666">+</span> <span style="color: #666666">0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n_samples,<span style="color: #666666">1</span>)
<span style="color: #408080; font-style: italic"># Centering x and y.</span>
x_ <span style="color: #666666">=</span> x <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(x)
y_ <span style="color: #666666">=</span> y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y) <span style="color: #408080; font-style: italic"># beta_0 = mean(y)</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((n_samples,<span style="color: #666666">1</span>)), x, x<span style="color: #666666">**2</span>]
X_ <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[x_, x_<span style="color: #666666">**2</span>]
<span style="color: #408080; font-style: italic">### 1.</span>
lmb_values <span style="color: #666666">=</span> [<span style="color: #666666">1e-4</span>, <span style="color: #666666">1e-3</span>, <span style="color: #666666">1e-2</span>, <span style="color: #666666">10</span>, <span style="color: #666666">1e2</span>, <span style="color: #666666">1e4</span>]
num_values <span style="color: #666666">=</span> <span style="color: #008000">len</span>(lmb_values)
<span style="color: #408080; font-style: italic">## Ridge-regression of centered and not centered data</span>
beta_ridge <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">3</span>,num_values))
beta_ridge_centered <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">3</span>,num_values))
I3 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">3</span>)
I2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">for</span> i,lmb <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmb_values):
beta_ridge[:,i] <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv( X<span style="color: #666666">.</span>T @ X <span style="color: #666666">+</span> lmb<span style="color: #666666">*</span>I3) @ X<span style="color: #666666">.</span>T @ y)<span style="color: #666666">.</span>flatten()
beta_ridge_centered[<span style="color: #666666">1</span>:,i] <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv( X_<span style="color: #666666">.</span>T @ X_ <span style="color: #666666">+</span> lmb<span style="color: #666666">*</span>I2) @ X_<span style="color: #666666">.</span>T @ y_)<span style="color: #666666">.</span>flatten()
<span style="color: #408080; font-style: italic"># sett beta_0 = np.mean(y)</span>
beta_ridge_centered[<span style="color: #666666">0</span>,:] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(y)
<span style="color: #408080; font-style: italic">## OLS (ordinary least squares) solution </span>
beta_ls <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv( X<span style="color: #666666">.</span>T @ X ) @ X<span style="color: #666666">.</span>T @ y
<span style="color: #408080; font-style: italic">## Evaluate the models</span>
pred_ls <span style="color: #666666">=</span> X @ beta_ls
pred_ridge <span style="color: #666666">=</span> X @ beta_ridge
pred_ridge_centered <span style="color: #666666">=</span> X_ @ beta_ridge_centered[<span style="color: #666666">1</span>:] <span style="color: #666666">+</span> beta_ridge_centered[<span style="color: #666666">0</span>,:]
<span style="color: #408080; font-style: italic">## Plot the results</span>
<span style="color: #408080; font-style: italic"># Sorting</span>
sort_ind <span style="color: #666666">=</span> np<span style="color: #666666">.</span>argsort(x[:,<span style="color: #666666">0</span>])
x_plot <span style="color: #666666">=</span> x[sort_ind,<span style="color: #666666">0</span>]
x_centered_plot <span style="color: #666666">=</span> x_[sort_ind,<span style="color: #666666">0</span>]
pred_ls_plot <span style="color: #666666">=</span> pred_ls[sort_ind,<span style="color: #666666">0</span>]
pred_ridge_plot <span style="color: #666666">=</span> pred_ridge[sort_ind,:]
pred_ridge_centered_plot <span style="color: #666666">=</span> pred_ridge_centered[sort_ind,:]
<span style="color: #408080; font-style: italic"># Plott not centered</span>
plt<span style="color: #666666">.</span>plot(x_plot,pred_ls_plot,label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;ls&#39;</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>(num_values):
plt<span style="color: #666666">.</span>plot(x_plot,pred_ridge_plot[:,i],label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;ridge, lmb=</span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>lmb_values[i])
plt<span style="color: #666666">.</span>plot(x,y,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;linear regression on un-centered data&#39;</span>)
plt<span style="color: #666666">.</span>legend()
<span style="color: #408080; font-style: italic"># Plott centered</span>
plt<span style="color: #666666">.</span>figure()
<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>(num_values):
plt<span style="color: #666666">.</span>plot(x_centered_plot,pred_ridge_centered_plot[:,i],label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;ridge, lmb=</span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>lmb_values[i])
plt<span style="color: #666666">.</span>plot(x_,y,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;linear regression on centered data&#39;</span>)
plt<span style="color: #666666">.</span>legend()
<span style="color: #408080; font-style: italic"># 2.</span>
pred_ridge_scikit <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n_samples,num_values))
<span style="color: #008000; font-weight: bold">for</span> i,lmb <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmb_values):
pred_ridge_scikit[:,i] <span style="color: #666666">=</span> (Ridge(alpha<span style="color: #666666">=</span>lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000">False</span>)<span style="color: #666666">.</span>fit(X,y)<span style="color: #666666">.</span>predict(X))<span style="color: #666666">.</span>flatten() <span style="color: #408080; font-style: italic"># fit_intercept=False fordi bias er allerede i X</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(x_plot,pred_ls_plot,label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;ls&#39;</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>(num_values):
plt<span style="color: #666666">.</span>plot(x_plot,pred_ridge_scikit[sort_ind,i],label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;scikit-ridge, lmb=</span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>lmb_values[i])
plt<span style="color: #666666">.</span>plot(x,y,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;linear regression using scikit&#39;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #408080; font-style: italic">### R2-score of the results</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>(num_values):
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;lambda = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>lmb_values[i])
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;r2 for scikit: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>r2_score(y,pred_ridge_scikit[:,i]))
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;r2 for own code, not centered: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>r2_score(y,pred_ridge[:,i]))
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;r2 for own, centered: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>r2_score(y,pred_ridge_centered[:,i]))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec44">Resampling methods </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<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.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec45">Resampling approaches can be computationally expensive </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<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.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec46">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</li>
<li> The results can be analysed with the same statistical tools as we would use 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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec47">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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec48">Statistics </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The <em>probability distribution function (PDF)</em> is a function
\( p(x) \) on the domain which, in the discrete case, gives us the
probability or relative frequency with which these values of \( X \) occur:
$$
p(x) = \mathrm{prob}(X=x)
$$
In the continuous case, the PDF does not directly depict the
actual probability. Instead we define the probability for the
stochastic variable to assume any value on an infinitesimal interval
around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us
the <em>density</em> of the probability rather than the probability
itself. The probability for a stochastic variable to assume any value
on a non-infinitesimal interval \( [a,\,b] \) is then just the integral:
$$
\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx
$$
Qualitatively speaking, a stochastic variable represents the values of
numbers chosen as if by chance from some specified PDF so that the
selection of a large set of these numbers reproduces this PDF.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec49">Statistics, moments </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
A particularly useful class of special expectation values are the
<em>moments</em>. The \( n \)-th moment of the PDF \( p \) is defined as
follows:
$$
\langle x^n\rangle \equiv \int\! x^n p(x)\,dx
$$
The zero-th moment \( \langle 1\rangle \) is just the normalization condition of
\( p \). The first moment, \( \langle x\rangle \), is called the <em>mean</em> of \( p \)
and often denoted by the letter \( \mu \):
$$
\langle x\rangle = \mu \equiv \int\! x p(x)\,dx
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec50">Statistics, central moments </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
A special version of the moments is the set of <em>central moments</em>,
the n-th central moment defined as:
$$
\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx
$$
The zero-th and first central moments are both trivial, equal \( 1 \) and
\( 0 \), respectively. But the second central moment, known as the
<em>variance</em> of \( p \), is of particular interest. For the stochastic
variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \):
$$
\begin{align}
\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle =
\int\! (x-\langle x\rangle)^2 p(x)\,dx
\label{_auto2}\\
& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} +
\langle x\rangle^2\right)p(x)\,dx
\label{_auto3}\\
& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2
\label{_auto4}\\
& = \langle x^2\rangle - \langle x\rangle^2
\label{_auto5}
\end{align}
$$
The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the <em>standard deviation</em> of \( p \). It is clearly just the RMS (root-mean-square)
value of the deviation of the PDF from its mean value, interpreted
qualitatively as the <em>spread</em> of \( p \) around its mean.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec51">Statistics, covariance </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Another important quantity is the so called covariance, a variant of
the above defined variance. Consider again the set \( \{X_i\} \) of \( n \)
stochastic variables (not necessarily uncorrelated) with the
multivariate PDF \( P(x_1,\dots,x_n) \). The <em>covariance</em> of two
of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows:
$$
\begin{align}
\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
\nonumber\\
&=
\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\,
P(x_1,\dots,x_n)\,dx_1\dots dx_n
\label{eq:def_covariance}
\end{align}
$$
with
$$
\langle x_i\rangle =
\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec52">Statistics, more covariance </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar
variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that
all the off-diagonal elements are zero if the stochastic variables are
uncorrelated. This is easy to show, keeping in mind the linearity of
the expectation value. Consider the stochastic variables \( X_i \) and
\( X_j \), (\( i\neq j \)):
$$
\begin{align}
\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
\label{_auto6}\\
&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle
\label{_auto7}\\
&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle +
\langle \langle x_i\rangle\langle x_j\rangle\rangle
\label{_auto8}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle +
\langle x_i\rangle\langle x_j\rangle
\label{_auto9}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle
\label{_auto10}
\end{align}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec53">Statistics, independent variables </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
If \( X_i \) and \( X_j \) are independent, we get
\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \).
<p>
Also useful for us is the covariance of linear combinations of
stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of
stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of
scalars. Consider the linear combination:
$$
U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j
$$
By the linearity of the expectation value
$$
\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j)
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec54">Statistics, more variance </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get
the variance of the linear combination \( U = \sum_i a_i X_i \):
$$
\begin{equation}
\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j)
\label{eq:variance_linear_combination}
\end{equation}
$$
And in the special case when the stochastic variables are
uncorrelated, the off-diagonal elements of the covariance are as we
know zero, resulting in:
$$
\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i)
$$
$$
\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i)
$$
which will become very useful in our study of the error in the mean
value of a set of measurements.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec55">Statistics and stochastic processes </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
A <em>stochastic process</em> is a process that produces sequentially a
chain of values:
$$
\{x_1, x_2,\dots\,x_k,\dots\}.
$$
We will call these
values our <em>measurements</em> and the entire set as our measured
<em>sample</em>. The action of measuring all the elements of a sample
we will call a stochastic <em>experiment</em> since, operationally,
they are often associated with results of empirical observation of
some physical or mathematical phenomena; precisely an experiment. We
assume that these values are distributed according to some
PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the
stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of
trying to determine the full distribution \( p \) we are often only
interested in finding the few lowest moments, like the mean
\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \).
</div>
<p>
<!-- !split -->
<h2 id="___sec56">Statistics and sample variables </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
In practical situations a sample is always of finite size. Let that
size be \( n \). The expectation value of a sample, the <em>sample mean</em>, is then defined as follows:
$$
\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k
$$
The <em>sample variance</em> is:
$$
\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2
$$
its square root being the <em>standard deviation of the sample</em>. The
<em>sample covariance</em> is:
$$
\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n)
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec57">Statistics, sample variance and covariance </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Note that the sample variance is the sample covariance without the
cross terms. In a similar manner as the covariance in Eq.&nbsp;\eqref{eq:def_covariance} is a measure of the correlation between
two stochastic variables, the above defined sample covariance is a
measure of the sequential correlation between succeeding measurements
of a sample.
<p>
These quantities, being known experimental values, differ
significantly from and must not be confused with the similarly named
quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \)
and covariance \( \mathrm{cov}(X,Y) \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec58">Statistics, law of large numbers </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The law of large numbers
states that as the size of our sample grows to infinity, the sample
mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF:
$$
\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X}
$$
The sample mean \( \bar{x}_n \) works therefore as an estimate of the true
mean \( \mu_X^{\phantom X} \).
<p>
What we need to find out is how good an approximation \( \bar{x}_n \) is to
\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated
mean is of no use to us without a measure of its error. A quantity
that tells us how well we can reproduce it in another experiment. We
are therefore interested in the PDF of the sample mean itself. Its
standard deviation will be a measure of the spread of sample means,
and we will simply call it the <em>error</em> of the sample mean, or
just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In
practice, we will only be able to produce an <em>estimate</em> of the
sample error since the exact value would require the knowledge of the
true PDFs behind, which we usually do not have.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec59">Statistics, more on sample error </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Let us first take a look at what happens to the sample error as the
size of the sample grows. In a sample, each of the measurements \( x_i \)
can be associated with its own stochastic variable \( X_i \). The
stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is
then just a linear combination, already familiar to us:
$$
\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i
$$
All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \),
denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample
means.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec60">Statistics </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The probability density of obtaining a sample mean \( \bar x_n \)
is the product of probabilities of obtaining arbitrary values \( x_1,
x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \)
is \( \bar x_n \):
$$
p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots
\int p_X^{\phantom X}(x_n)\
\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1
$$
And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec61">Statistics, central limit theorem </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
It is generally not possible to express \( p_{\overline X_n}(x) \) in a
closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number
\( n \). But for the limit \( n\to\infty \) it is possible to make an
approximation. The very important result is called <em>the central limit theorem</em>. It tells us that as \( n \) goes to infinity,
\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean
and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \)
and \( \sigma_{X}^{2} \), respectively:
$$
\begin{equation}
\lim_{n\to\infty} p_{\overline X_n}(x) =
\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2}
e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}}
\label{eq:central_limit_gaussian}
\end{equation}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec62">Statistics, more technicalities </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The desired variance
\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared
\( \mathrm{err}_X^2 \), is given by:
$$
\begin{equation}
\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2}
\sum_{ij} \mathrm{cov}(X_i, X_j)
\label{eq:error_exact}
\end{equation}
$$
We see now that in order to calculate the exact error of the sample
with the above expression, we would need the true means
\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To
calculate these requires that we know the true multivariate PDF of all
the \( X_i \). But this PDF is unknown to us, we have only got the measurements of
one sample. The best we can do is to let the sample itself be an
estimate of the PDF of each of the \( X_i \), estimating all properties of
\( X_i \) through the measurements of the sample.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec63">Statistics </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \)
itself, in accordance with the the central limit theorem:
$$
\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x
$$
Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an
<em>estimate</em> of the covariance in Eq.&nbsp;\eqref{eq:error_exact}
$$
\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle,
$$
resulting in
$$
\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x)
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec64">Statistics and sample variance </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
By the same procedure we can use the sample variance as an
estimate of the variance of any of the stochastic variables \( X_i \)
$$
\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber,
$$
which is approximated as
$$
\begin{equation}
\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x)
\label{eq:var_estimate_i_think}
\end{equation}
$$
<p>
Now we can calculate an estimate of the error
\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \):
$$
\begin{align}
\mathrm{err}_X^2
&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\
&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\
&=\frac{1}{n}\mathrm{cov}(x)
\label{eq:error_estimate}
\end{align}
$$
which is nothing but the sample covariance divided by the number of
measurements in the sample.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec65">Statistics, uncorrelated results </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
In the special case that the measurements of the sample are
uncorrelated (equivalently the stochastic variables \( X_i \) are
uncorrelated) we have that the off-diagonal elements of the covariance
are zero. This gives the following estimate of the sample error:
$$
\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) =
\frac{1}{n^2} \sum_i \mathrm{var}(X_i),
$$
resulting in
$$
\begin{equation}
\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x)
\label{eq:error_estimate_uncorrel}
\end{equation}
$$
where in the second step we have used Eq.&nbsp;\eqref{eq:var_estimate_i_think}.
The error of the sample is then just its standard deviation divided by
the square root of the number of measurements the sample contains.
This is a very useful formula which is easy to compute. It acts as a
first approximation to the error, but in numerical experiments, we
cannot overlook the always present correlations.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec66">Statistics, computations </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
For computational purposes one usually splits up the estimate of
\( \mathrm{err}_X^2 \), given by Eq.&nbsp;\eqref{eq:error_estimate}, into two
parts
$$
\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)),
$$
which equals
$$
\begin{equation}
\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n)
\label{eq:error_estimate_split_up}
\end{equation}
$$
The first term is the same as the error in the uncorrelated case,
Eq.&nbsp;\eqref{eq:error_estimate_uncorrel}. This means that the second
term accounts for the error correction due to correlation between the
measurements. For uncorrelated measurements this second term is zero.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec67">Statistics, more on computations of errors </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Computationally the uncorrelated first term is much easier to treat
efficiently than the second.
$$
\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 =
\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2
$$
We just accumulate separately the values \( x^2 \) and \( x \) for every
measurement \( x \) we receive. The correlation term, though, has to be
calculated at the end of the experiment since we need all the
measurements to calculate the cross terms. Therefore, all measurements
have to be stored throughout the experiment.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec68">Statistics, wrapping up 1 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Let us analyze the problem by splitting up the correlation term into
partial sums of the form:
$$
f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n)
$$
The correlation term of the error can now be rewritten in terms of
\( f_d \)
$$
\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) =
2\sum_{d=1}^{n-1} f_d
$$
The value of \( f_d \) reflects the correlation between measurements
separated by the distance \( d \) in the sample samples. Notice that for
\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \)
by \( \mathrm{var}(x) \), we arrive at the so called <em>autocorrelation function</em>
$$
\kappa_d = \frac{f_d}{\mathrm{var}(x)}
$$
which gives us a useful measure of pairwise correlations
starting always at \( 1 \) for \( d=0 \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec69">Statistics, final expression </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The sample error (see eq.&nbsp;\eqref{eq:error_estimate_split_up}) can now be
written in terms of the autocorrelation function:
$$
\begin{align}
\mathrm{err}_X^2 &=
\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1}
\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=&
\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\
&=\frac{\tau}{n}\cdot\mathrm{var}(x)
\label{eq:error_estimate_corr_time}
\end{align}
$$
and we see that \( \mathrm{err}_X \) can be expressed in terms the
uncorrelated sample variance times a correction factor \( \tau \) which
accounts for the correlation between measurements. We call this
correction factor the <em>autocorrelation time</em>:
$$
\begin{equation}
\tau = 1+2\sum_{d=1}^{n-1}\kappa_d
\label{eq:autocorrelation_time}
\end{equation}
$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec70">Statistics, effective number of correlations </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
For a correlation free experiment, \( \tau \)
equals 1. From the point of view of
eq.&nbsp;\eqref{eq:error_estimate_corr_time} we can interpret a sequential
correlation as an effective reduction of the number of measurements by
a factor \( \tau \). The effective number of measurements becomes:
$$
n_\mathrm{eff} = \frac{n}{\tau}
$$
To neglect the autocorrelation time \( \tau \) will always cause our
simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to
be less than the true sample error. The estimate of the error will be
too <em>good</em>. On the other hand, the calculation of the full
autocorrelation time poses an efficiency problem if the set of
measurements is very large.
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec71">Log-likelihood </h2>
<p>
A popular strategy is to choose a penalty parameter that yields a good
but parsimonious model. Information criteria measure the balance
between model fit and model complexity. One possibility is Aikaike's
information criterion (AIC).
The AIC measures model fit by the log-likelihood
and model complexity is measured by the number of parameters used by
the model. The number of model parameters in regular regression simply
corresponds to the number of covariates in the model. Or, by the
degrees of freedom consumed by the model, which is equivalent to the
trace of the hat matrix. For ridge regression it thus seems natural to
define model complexity analogously by the trace of the ridge hat
matrix. This yields the AIC for the linear regression model with ridge
estimates:
$$
\begin{align*}
\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L})
\\
& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\}
\\
& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda}
+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2.
\end{align*}
$$
The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting.
<p>
<!-- !split -->
<h2 id="___sec72">Cross-validation </h2>
<p>
Instead of choosing the penalty parameter to balance model fit with
model complexity, cross-validation requires it (i.e. the penalty
parameter) to yield a model with good prediction
performance. Commonly, this performance is evaluated on novel
data. Novel data need not be easy to come by and one has to make do
with the data at hand. The setting of `original' and novel data is
then mimicked by sample splitting: the data set is divided into two
(groups of samples). One of these two data sets, called the <em>training
set</em>, plays the role of `original' data on which the model is
built. The second of these data sets, called the <em>test set</em>, plays the
role of the `novel' data and is used to evaluate the prediction
performance (often operationalized as the log-likelihood or the
prediction error or its square or the R2 score) of the model built on the training data set. This
procedure (model building and prediction evaluation on training and
test set, respectively) is done for a collection of possible penalty
parameter choices. The penalty parameter that yields the model with
the best prediction performance is to be preferred. The thus obtained
performance evaluation depends on the actual split of the data set. To
remove this dependence the data set is split many times into a
training and test set. For each split the model parameters are
estimated for all choices of \( \lambda \) using the training data and
estimated parameters are evaluated on the corresponding test set. The
penalty parameter that on average over the test sets performs best (in
some sense) is then selected.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec73">Computationally expensive </h2>
<p>
The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:
<ul>
<li> The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.</li>
<li> In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.</li>
</ul>
<!-- !split -->
<h2 id="___sec74">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 -->
<h2 id="___sec75">How to set up the cross-validation for Ridge and/or Lasso </h2>
<ul>
<li> Define a range of interest for the penalty parameter.</li>
<li> Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.</li>
<li> Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \hat{\sigma}_{-i}^2(\lambda) \), as</li>
</ul>
$$
\begin{align*}
\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top}
\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1}
\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i}
\end{align*}
$$
<ul>
<li> Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.</li>
<li> Repeat the first three steps such that each sample plays the role of the test set once.</li>
<li> Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the <em>cross-validated log-likelihood</em>. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as</li>
</ul>
$$
\begin{align*}
\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}.
\end{align*}
$$
<ul>
<li> The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec76">Predicted Residual Error Sum of Squares </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS).
<p>
We can define the optimal penalty parameter to minimize
$$
\begin{align*}
\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2.
\end{align*}
$$
<p>
The LOOCV prediction performance can be
expressed analytically in terms of the known quantities derived from
the design matrix and the parameters \( \beta \).
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec77">Resampling methods: Jackknife and Bootstrap </h2>
<p>
Two famous
resampling methods are the <b>independent bootstrap</b> and <b>the jackknife</b>.
<p>
The jackknife is a special case of the independent bootstrap. Still, the jackknife was made
popular prior to the independent bootstrap. And as the popularity of
the independent bootstrap soared, new variants, such as <b>the dependent bootstrap</b>.
<p>
The Jackknife and independent bootstrap work for
independent, identically distributed random variables.
If these conditions are not
satisfied, the methods will fail. Yet, it should be said that if the data are
independent, identically distributed, and we only want to estimate the
variance of \( \overline{X} \) (which often is the case), then there is no
need for bootstrapping.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec78">Resampling methods: Jackknife </h2>
<p>
The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \).
The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \).
Let \( \hat{x}_i \) denote the vector
$$
\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
$$
<p>
which equals the vector \( \hat{x} \) with the exception that observation
number \( i \) is left out. Using this notation, define
\( \widehat{\theta}_i \) to be the estimator
\( \widehat{\theta} \) computed using \( \vec{X}_i \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec79">Resampling methods: Jackknife estimator </h2>
<p>
To get an estimate for the bias and
standard error of \( \widehat{\theta} \), use the following
estimators for each component of \( \widehat{\theta} \)
$$
\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec80">Jackknife code example </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">import</span> <span style="color: #666666">*</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">numpy.random</span> <span style="color: #008000; font-weight: bold">import</span> randint, randn
<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">def</span> <span style="color: #0000FF">jackknife</span>(data, stat):
n <span style="color: #666666">=</span> <span style="color: #008000">len</span>(data);t <span style="color: #666666">=</span> zeros(n); inds <span style="color: #666666">=</span> arange(n); t0 <span style="color: #666666">=</span> time()
<span style="color: #408080; font-style: italic">## &#39;jackknifing&#39; by leaving out an observation for each i </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>(n):
t[i] <span style="color: #666666">=</span> stat(delete(data,i) )
<span style="color: #408080; font-style: italic"># analysis </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Runtime: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> sec&quot;</span> <span style="color: #666666">%</span> (time()<span style="color: #666666">-</span>t0)); <span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Jackknife Statistics :&quot;</span>)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;original bias std. error&quot;</span>)
<span style="color: #008000; font-weight: bold">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">%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> (stat(data),(n<span style="color: #666666">-1</span>)<span style="color: #666666">*</span>mean(t)<span style="color: #666666">/</span>n, (n<span style="color: #666666">*</span>var(t))<span style="color: #666666">**.5</span>))
<span style="color: #008000; font-weight: bold">return</span> t
<span style="color: #408080; font-style: italic"># Returns mean of data samples </span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">stat</span>(data):
<span style="color: #008000; font-weight: bold">return</span> mean(data)
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>
x <span style="color: #666666">=</span> mu <span style="color: #666666">+</span> sigma<span style="color: #666666">*</span>random<span style="color: #666666">.</span>randn(datapoints)
<span style="color: #408080; font-style: italic"># jackknife returns the data sample </span>
t <span style="color: #666666">=</span> jackknife(x, stat)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec81">Resampling methods: Bootstrap </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Bootstrapping is a nonparametric approach to statistical inference
that substitutes computation for more traditional distributional
assumptions and asymptotic results. Bootstrapping offers a number of
advantages:
<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec82">Resampling methods: Bootstrap background </h2>
<p>
Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables,
\( \widehat{\theta} \) itself must be a random variable. Thus it has
a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to
estimate \( p(\hat{t}) \) by the relative frequency of
\( \widehat{\theta} \). You can think of this as using a histogram
in the place of \( p(\hat{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(\hat{t}) \) using point
estimators.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec83">Resampling methods: More Bootstrap background </h2>
<p>
In the case that \( \widehat{\theta} \) 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 straight forward to do this by:
<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{\theta} \) called \( \widehat{\theta}^* \).</li>
</ol>
By repeated use of (1) and (2), many
estimates of \( \widehat{\theta} \) could have been obtained. The
idea is to use the relative frequency of \( \widehat{\theta}^* \)
(think of a histogram) as an estimate of \( p(\hat{t}) \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec84">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 \); 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>
Instead of generating the histogram for the relative
frequency of the observation \( X_i \), just draw the values
\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector
\( \hat{X} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec85">Resampling methods: Bootstrap steps </h2>
<p>
The independent bootstrap works like this:
<ol>
<li> Draw with replacement \( n \) numbers for the observed variables \( \hat{x} = (x_1,x_2,\cdots,x_n) \).</li>
<li> Define a vector \( \hat{x}^* \) containing the values which were drawn from \( \hat{x} \).</li>
<li> Using the vector \( \hat{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \hat{x}^* \).</li>
<li> Repeat this process \( k \) times.</li>
</ol>
When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). 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{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec86">Code example for the Bootstrap method </h2>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">import</span> <span style="color: #666666">*</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">numpy.random</span> <span style="color: #008000; font-weight: bold">import</span> randint, randn
<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">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.mlab</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">mlab</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: #408080; font-style: italic"># Returns mean of bootstrap samples </span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">stat</span>(data):
<span style="color: #008000; font-weight: bold">return</span> mean(data)
<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, statistic, R):
t <span style="color: #666666">=</span> zeros(R); n <span style="color: #666666">=</span> <span style="color: #008000">len</span>(data); inds <span style="color: #666666">=</span> arange(n); t0 <span style="color: #666666">=</span> time()
<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>(R):
t[i] <span style="color: #666666">=</span> statistic(data[randint(<span style="color: #666666">0</span>,n,n)])
<span style="color: #408080; font-style: italic"># analysis </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Runtime: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121"> sec&quot;</span> <span style="color: #666666">%</span> (time()<span style="color: #666666">-</span>t0)); <span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Bootstrap Statistics :&quot;</span>)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;original bias std. error&quot;</span>)
<span style="color: #008000; font-weight: bold">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> (statistic(data), std(data),\
mean(t), \
std(t)))
<span style="color: #008000; font-weight: bold">return</span> t
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>
x <span style="color: #666666">=</span> mu <span style="color: #666666">+</span> sigma<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 t = bootstrap(x, stat, datapoints)</span>
<span style="color: #408080; font-style: italic"># the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor=&#39;red&#39;, alpha=0.75)</span>
<span style="color: #408080; font-style: italic"># add a &#39;best fit&#39; line </span>
y <span style="color: #666666">=</span> mlab<span style="color: #666666">.</span>normpdf( binsboot, mean(t), std(t))
lt <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>plot(binsboot, y, <span style="color: #BA2121">&#39;r--&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Smarts&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Probability&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">99.5</span>, <span style="color: #666666">100.6</span>, <span style="color: #666666">0</span>, <span style="color: #666666">3.0</span>])
plt<span style="color: #666666">.</span>grid(<span style="color: #008000">True</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec87">Resampling methods: Blocking </h2>
<p>
The blocking method was made popular by <a href="https://aip.scitation.org/doi/10.1063/1.457480" target="_blank">Flyvbjerg and Pedersen (1989)</a>
and has become one of the standard ways to estimate
\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely
\( \widehat{\theta} = \overline{X} \).
<p>
Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with.
Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define:
$$
\begin{align*}
\hat{X} = (X_1,X_2,\cdots,X_n).
\end{align*}
$$
<p>
The strength of the blocking method is when the number of
observations, \( n \) is large. For large \( n \), the complexity of dependent
bootstrapping scales poorly, but the blocking method does not,
moreover, it becomes more accurate the larger \( n \) is.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec88">Blocking Transformations </h2>
We now define
blocking transformations. The idea is to take the mean of subsequent
pair of elements from \( \vec{X} \) and form a new vector
\( \vec{X}_1 \). Continuing in the same way by taking the mean of
subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and
so on.
Define \( \vec{X}_i \) recursively by:
$$
\begin{align}
(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\
(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} +
(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1
\label{_auto11}
\end{align}
$$
<p>
The quantity \( \vec{X}_k \) is
subject to \( k \) <b>blocking transformations</b>. We now have \( d \) vectors
\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent
averages of observations. It turns out that if the components of
\( \vec{X} \) is a stationary time series, then the components of
\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \)
<p>
We can then compute the autocovariance, the variance, sample mean, and
number of observations for each \( i \).
Let \( \gamma_i, \sigma_i^2,
\overline{X}_i \) denote the autocovariance, variance and average of the
elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of
\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec89">Blocking Transformations </h2>
<p>
Using the
definition of the blocking transformation and the distributive
property of the covariance, it is clear that since \( h =|i-j| \)
we can define
$$
\begin{align}
\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\
&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\
&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0}
\label{_auto12}\\
&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else}
\label{_auto13}
\end{align}
$$
<p>
The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec90">Blocking Transformations, getting there </h2>
We have
$$
\begin{align}
V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2.
\label{_auto14}
\end{align}
$$
The term \( e_k \) is called the <b>truncation error</b>:
$$
\begin{equation}
e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h).
\label{_auto15}
\end{equation}
$$
We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec91">Blocking Transformations, final expressions </h2>
<p>
We can then wrap up
$$
\begin{align}
n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\
&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j.
\label{_auto16}
\end{align}
$$
By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that
$$
\begin{align}
V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence}
\end{align}
$$
<p>
Fyvbjerg and Petersen demonstrated that the sequence
\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term
\( e_k \) can be made as small as we would like by making \( k \) (and hence
\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).
It means we can apply blocking transformations until
\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by
\( \widehat{\sigma}^2_k/n_k \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec92"><a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts" target="_blank">Code examples for Blocking, Jackknife and bootstrap</a> </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sys</span> <span style="color: #008000; font-weight: bold">import</span> argv
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">os</span> <span style="color: #008000; font-weight: bold">import</span> mkdir, path
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">time</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">matplotlib.ticker</span> <span style="color: #008000; font-weight: bold">import</span> FormatStrFormatter
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.font_manager</span> <span style="color: #008000; font-weight: bold">import</span> FontProperties
<span style="color: #408080; font-style: italic"># Timing Decorator</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">timeFunction</span>(f):
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">wrap</span>(<span style="color: #666666">*</span>args):
time1 <span style="color: #666666">=</span> time<span style="color: #666666">.</span>time()
ret <span style="color: #666666">=</span> f(<span style="color: #666666">*</span>args)
time2 <span style="color: #666666">=</span> time<span style="color: #666666">.</span>time()
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&#39;</span><span style="color: #BB6688; font-weight: bold">%s</span><span style="color: #BA2121"> Function Took: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121"> </span><span style="color: #BB6688; font-weight: bold">%0.3f</span><span style="color: #BA2121"> s&#39;</span> <span style="color: #666666">%</span> (f<span style="color: #666666">.</span>func_name<span style="color: #666666">.</span>title(), (time2<span style="color: #666666">-</span>time1))
<span style="color: #008000; font-weight: bold">return</span> ret
<span style="color: #008000; font-weight: bold">return</span> wrap
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">dataAnalysisClass</span>:
<span style="color: #408080; font-style: italic"># General Init functions</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, fileName, size<span style="color: #666666">=0</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>inputFileName <span style="color: #666666">=</span> fileName
<span style="color: #008000">self</span><span style="color: #666666">.</span>loadData(size)
<span style="color: #008000">self</span><span style="color: #666666">.</span>createOutputFolder()
<span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)
<span style="color: #008000">self</span><span style="color: #666666">.</span>var <span style="color: #666666">=</span> np<span style="color: #666666">.</span>var(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)
<span style="color: #008000">self</span><span style="color: #666666">.</span>std <span style="color: #666666">=</span> np<span style="color: #666666">.</span>std(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">loadData</span>(<span style="color: #008000">self</span>, size<span style="color: #666666">=0</span>):
<span style="color: #008000; font-weight: bold">if</span> size <span style="color: #666666">!=</span> <span style="color: #666666">0</span>:
<span style="color: #008000; font-weight: bold">with</span> <span style="color: #008000">open</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>inputFileName) <span style="color: #008000; font-weight: bold">as</span> inputFile:
<span style="color: #008000">self</span><span style="color: #666666">.</span>data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(size)
<span style="color: #008000; font-weight: bold">for</span> x <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">xrange</span>(size):
<span style="color: #008000">self</span><span style="color: #666666">.</span>data[x] <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">next</span>(inputFile))
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000">self</span><span style="color: #666666">.</span>data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>loadtxt(<span style="color: #008000">self</span><span style="color: #666666">.</span>inputFileName)
<span style="color: #408080; font-style: italic"># Statistical Analysis with Multiple Methods</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">runAllAnalyses</span>(<span style="color: #008000">self</span>):
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data) <span style="color: #666666">&lt;=</span> <span style="color: #666666">100000</span>:
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Autocorrelation...&quot;</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>autocorrelation()
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Bootstrap...&quot;</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>bootstrap()
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Jackknife...&quot;</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>jackknife()
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Blocking...&quot;</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>blocking()
<span style="color: #408080; font-style: italic"># Standard Autocorrelation</span>
<span style="color: #AA22FF">@timeFunction</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">autocorrelation</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>acf <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)<span style="color: #666666">/2</span>)
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)<span style="color: #666666">/2</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>acf[k] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>corrcoef(np<span style="color: #666666">.</span>array([<span style="color: #008000">self</span><span style="color: #666666">.</span>data[<span style="color: #666666">0</span>:<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)<span style="color: #666666">-</span>k], \
<span style="color: #008000">self</span><span style="color: #666666">.</span>data[k:<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)]]))[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]
<span style="color: #408080; font-style: italic"># Bootstrap</span>
<span style="color: #AA22FF">@timeFunction</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">bootstrap</span>(<span style="color: #008000">self</span>, nBoots <span style="color: #666666">=</span> <span style="color: #666666">1000</span>):
bootVec <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nBoots)
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">0</span>,nBoots):
bootVec[k] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(<span style="color: #008000">self</span><span style="color: #666666">.</span>data, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)))
<span style="color: #008000">self</span><span style="color: #666666">.</span>bootAvg <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(bootVec)
<span style="color: #008000">self</span><span style="color: #666666">.</span>bootVar <span style="color: #666666">=</span> np<span style="color: #666666">.</span>var(bootVec)
<span style="color: #008000">self</span><span style="color: #666666">.</span>bootStd <span style="color: #666666">=</span> np<span style="color: #666666">.</span>std(bootVec)
<span style="color: #408080; font-style: italic"># Jackknife</span>
<span style="color: #AA22FF">@timeFunction</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">jackknife</span>(<span style="color: #008000">self</span>):
jackknVec <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data))
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">0</span>,<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)):
jackknVec[k] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(np<span style="color: #666666">.</span>delete(<span style="color: #008000">self</span><span style="color: #666666">.</span>data, k))
<span style="color: #008000">self</span><span style="color: #666666">.</span>jackknAvg <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">-</span> (<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data) <span style="color: #666666">-</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> (np<span style="color: #666666">.</span>average(jackknVec) <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>avg)
<span style="color: #008000">self</span><span style="color: #666666">.</span>jackknVar <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data) <span style="color: #666666">-</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>var(jackknVec)
<span style="color: #008000">self</span><span style="color: #666666">.</span>jackknStd <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sqrt(<span style="color: #008000">self</span><span style="color: #666666">.</span>jackknVar)
<span style="color: #408080; font-style: italic"># Blocking</span>
<span style="color: #AA22FF">@timeFunction</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">blocking</span>(<span style="color: #008000">self</span>, blockSizeMax <span style="color: #666666">=</span> <span style="color: #666666">500</span>):
blockSizeMin <span style="color: #666666">=</span> <span style="color: #666666">1</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>blockSizes <span style="color: #666666">=</span> []
<span style="color: #008000">self</span><span style="color: #666666">.</span>meanVec <span style="color: #666666">=</span> []
<span style="color: #008000">self</span><span style="color: #666666">.</span>varVec <span style="color: #666666">=</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>(blockSizeMin, blockSizeMax):
<span style="color: #008000; font-weight: bold">if</span>(<span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data) <span style="color: #666666">%</span> i <span style="color: #666666">!=</span> <span style="color: #666666">0</span>):
<span style="color: #008000; font-weight: bold">pass</span><span style="color: #408080; font-style: italic">#continue</span>
blockSize <span style="color: #666666">=</span> i
meanTempVec <span style="color: #666666">=</span> []
varTempVec <span style="color: #666666">=</span> []
startPoint <span style="color: #666666">=</span> <span style="color: #666666">0</span>
endPoint <span style="color: #666666">=</span> blockSize
<span style="color: #008000; font-weight: bold">while</span> endPoint <span style="color: #666666">&lt;=</span> <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data):
meanTempVec<span style="color: #666666">.</span>append(np<span style="color: #666666">.</span>average(<span style="color: #008000">self</span><span style="color: #666666">.</span>data[startPoint:endPoint]))
startPoint <span style="color: #666666">=</span> endPoint
endPoint <span style="color: #666666">+=</span> blockSize
mean, var <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(meanTempVec), np<span style="color: #666666">.</span>var(meanTempVec)<span style="color: #666666">/</span><span style="color: #008000">len</span>(meanTempVec)
<span style="color: #008000">self</span><span style="color: #666666">.</span>meanVec<span style="color: #666666">.</span>append(mean)
<span style="color: #008000">self</span><span style="color: #666666">.</span>varVec<span style="color: #666666">.</span>append(var)
<span style="color: #008000">self</span><span style="color: #666666">.</span>blockSizes<span style="color: #666666">.</span>append(blockSize)
<span style="color: #008000">self</span><span style="color: #666666">.</span>blockingAvg <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(<span style="color: #008000">self</span><span style="color: #666666">.</span>meanVec[<span style="color: #666666">-200</span>:])
<span style="color: #008000">self</span><span style="color: #666666">.</span>blockingVar <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>average(<span style="color: #008000">self</span><span style="color: #666666">.</span>varVec[<span style="color: #666666">-200</span>:]))
<span style="color: #008000">self</span><span style="color: #666666">.</span>blockingStd <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sqrt(<span style="color: #008000">self</span><span style="color: #666666">.</span>blockingVar)
<span style="color: #408080; font-style: italic"># Plot of Data, Autocorrelation Function and Histogram</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plotAll</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>createOutputFolder()
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data) <span style="color: #666666">&lt;=</span> <span style="color: #666666">100000</span>:
<span style="color: #008000">self</span><span style="color: #666666">.</span>plotAutocorrelation()
<span style="color: #008000">self</span><span style="color: #666666">.</span>plotData()
<span style="color: #008000">self</span><span style="color: #666666">.</span>plotHistogram()
<span style="color: #008000">self</span><span style="color: #666666">.</span>plotBlocking()
<span style="color: #408080; font-style: italic"># Create Output Plots Folder</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">createOutputFolder</span>(<span style="color: #008000">self</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>inputFileName[:<span style="color: #666666">-4</span>]
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> path<span style="color: #666666">.</span>exists(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName):
mkdir(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName)
<span style="color: #408080; font-style: italic"># Plot the Dataset, Mean and Std</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plotData</span>(<span style="color: #008000">self</span>):
<span style="color: #408080; font-style: italic"># Far away plot</span>
font <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;fontname&#39;</span>:<span style="color: #BA2121">&#39;serif&#39;</span>}
plt<span style="color: #666666">.</span>plot(<span style="color: #008000">range</span>(<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)), <span style="color: #008000">self</span><span style="color: #666666">.</span>data, <span style="color: #BA2121">&#39;r-&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)], [<span style="color: #008000">self</span><span style="color: #666666">.</span>avg, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg], <span style="color: #BA2121">&#39;b-&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)], [<span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>std, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">+</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>std], <span style="color: #BA2121">&#39;g--&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)], [<span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>std, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>std], <span style="color: #BA2121">&#39;g--&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>ylim(<span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">-</span> <span style="color: #666666">5*</span><span style="color: #008000">self</span><span style="color: #666666">.</span>std, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">+</span> <span style="color: #666666">5*</span><span style="color: #008000">self</span><span style="color: #666666">.</span>std)
plt<span style="color: #666666">.</span>gca()<span style="color: #666666">.</span>yaxis<span style="color: #666666">.</span>set_major_formatter(FormatStrFormatter(<span style="color: #BA2121">&#39;</span><span style="color: #BB6688; font-weight: bold">%.4f</span><span style="color: #BA2121">&#39;</span>))
plt<span style="color: #666666">.</span>xlim(<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data))
plt<span style="color: #666666">.</span>ylabel(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName<span style="color: #666666">.</span>title() <span style="color: #666666">+</span> <span style="color: #BA2121">&#39; Monte Carlo Evolution&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;MonteCarlo History&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>title(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName<span style="color: #666666">.</span>title(), <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/data.eps&quot;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/data.png&quot;</span>)
plt<span style="color: #666666">.</span>clf()
<span style="color: #408080; font-style: italic"># Plot Histogram of Dataset and Gaussian around it</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plotHistogram</span>(<span style="color: #008000">self</span>):
binNumber <span style="color: #666666">=</span> <span style="color: #666666">50</span>
font <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;fontname&#39;</span>:<span style="color: #BA2121">&#39;serif&#39;</span>}
count, bins, ignore <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>hist(<span style="color: #008000">self</span><span style="color: #666666">.</span>data, bins<span style="color: #666666">=</span>np<span style="color: #666666">.</span>linspace(<span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">-</span> <span style="color: #666666">5*</span><span style="color: #008000">self</span><span style="color: #666666">.</span>std, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg <span style="color: #666666">+</span> <span style="color: #666666">5*</span><span style="color: #008000">self</span><span style="color: #666666">.</span>std, binNumber))
plt<span style="color: #666666">.</span>plot([<span style="color: #008000">self</span><span style="color: #666666">.</span>avg, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg], [<span style="color: #666666">0</span>,np<span style="color: #666666">.</span>max(count)<span style="color: #666666">+10</span>], <span style="color: #BA2121">&#39;b-&#39;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">0</span>,np<span style="color: #666666">.</span>max(count)<span style="color: #666666">+10</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName<span style="color: #666666">.</span>title() <span style="color: #666666">+</span> <span style="color: #BA2121">&#39; Histogram&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName<span style="color: #666666">.</span>title() , <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Counts&#39;</span>, <span style="color: #666666">**</span>font)
<span style="color: #408080; font-style: italic">#gaussian</span>
norm <span style="color: #666666">=</span> <span style="color: #666666">0</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: #666666">0</span>,<span style="color: #008000">len</span>(bins)<span style="color: #666666">-1</span>):
norm <span style="color: #666666">+=</span> (bins[i<span style="color: #666666">+1</span>]<span style="color: #666666">-</span>bins[i])<span style="color: #666666">*</span>count[i]
plt<span style="color: #666666">.</span>plot(bins, norm<span style="color: #666666">/</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>std <span style="color: #666666">*</span> np<span style="color: #666666">.</span>sqrt(<span style="color: #666666">2</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>pi)) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp( <span style="color: #666666">-</span> (bins <span style="color: #666666">-</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>avg)<span style="color: #666666">**2</span> <span style="color: #666666">/</span> (<span style="color: #666666">2</span> <span style="color: #666666">*</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>std<span style="color: #666666">**2</span>) ), linewidth<span style="color: #666666">=1</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;r&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/hist.eps&quot;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/hist.png&quot;</span>)
plt<span style="color: #666666">.</span>clf()
<span style="color: #408080; font-style: italic"># Plot the Autocorrelation Function</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plotAutocorrelation</span>(<span style="color: #008000">self</span>):
font <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;fontname&#39;</span>:<span style="color: #BA2121">&#39;serif&#39;</span>}
plt<span style="color: #666666">.</span>plot(<span style="color: #008000">range</span>(<span style="color: #666666">1</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)<span style="color: #666666">/2</span>), <span style="color: #008000">self</span><span style="color: #666666">.</span>acf[<span style="color: #666666">1</span>:], <span style="color: #BA2121">&#39;r-&#39;</span>)
plt<span style="color: #666666">.</span>ylim(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
plt<span style="color: #666666">.</span>xlim(<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)<span style="color: #666666">/2</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Autocorrelation Function&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Lag&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Autocorrelation&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/autocorrelation.eps&quot;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/autocorrelation.png&quot;</span>)
plt<span style="color: #666666">.</span>clf()
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plotBlocking</span>(<span style="color: #008000">self</span>):
font <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;fontname&#39;</span>:<span style="color: #BA2121">&#39;serif&#39;</span>}
plt<span style="color: #666666">.</span>plot(<span style="color: #008000">self</span><span style="color: #666666">.</span>blockSizes, <span style="color: #008000">self</span><span style="color: #666666">.</span>varVec, <span style="color: #BA2121">&#39;r-&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Variance&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Block Size&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&#39;Blocking&#39;</span>, <span style="color: #666666">**</span>font)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/blocking.eps&quot;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #008000">self</span><span style="color: #666666">.</span>outName <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;/blocking.png&quot;</span>)
plt<span style="color: #666666">.</span>clf()
<span style="color: #408080; font-style: italic"># Print Stuff to the Terminal</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">printOutput</span>(<span style="color: #008000">self</span>):
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">Sample Size: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">len</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>data)
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">=========================================</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&quot;</span>
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Sample Average: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>avg
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Sample Variance:</span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>var
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Sample Std: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>std
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">=========================================</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&quot;</span>
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Bootstrap Average: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>bootAvg
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Bootstrap Variance:</span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>bootVar
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Bootstrap Error: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>bootStd
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">=========================================</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&quot;</span>
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Jackknife Average: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>jackknAvg
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Jackknife Variance:</span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>jackknVar
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Jackknife Error: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>jackknStd
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">=========================================</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&quot;</span>
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Blocking Average: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>blockingAvg
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Blocking Variance:</span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>blockingVar
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&quot;Blocking Error: </span><span style="color: #BB6622; font-weight: bold">\t</span><span style="color: #BA2121">&quot;</span>, <span style="color: #008000">self</span><span style="color: #666666">.</span>blockingStd, <span style="color: #BA2121">&quot;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&quot;</span>
<span style="color: #408080; font-style: italic"># Initialize the class</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(argv) <span style="color: #666666">&gt;</span> <span style="color: #666666">2</span>:
dataAnalysis <span style="color: #666666">=</span> dataAnalysisClass(argv[<span style="color: #666666">1</span>], <span style="color: #008000">int</span>(argv[<span style="color: #666666">2</span>]))
<span style="color: #008000; font-weight: bold">else</span>:
dataAnalysis <span style="color: #666666">=</span> dataAnalysisClass(argv[<span style="color: #666666">1</span>])
<span style="color: #408080; font-style: italic"># Run Analyses</span>
dataAnalysis<span style="color: #666666">.</span>runAllAnalyses()
<span style="color: #408080; font-style: italic"># Plot the data</span>
dataAnalysis<span style="color: #666666">.</span>plotAll()
<span style="color: #408080; font-style: italic"># Print Some Output</span>
dataAnalysis<span style="color: #666666">.</span>printOutput()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec93">The bias-variance tradeoff </h2>
<p>
We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set}
\( \mathcal{H} \) consisting of all functions we are willing to consider,
defined also on the domain of \( f \). This set may be uncountably
infinite (e.g.&nbsp;if there are real-valued parameters to fit).
The
choice of which functions to include in \( \mathcal{H} \) usually depends
on our intuition about the problem of interest. The function \( f(x) \)
produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the
observable data. Our goal is to select a function from the hypothesis
set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible,
namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx
f \) in some strict mathematical sense which we specify below. If this
is possible, we say that we \emph{learned} \( f(x) \). But if the
function \( f(x) \) can, in principle, take any value on
\emph{unobserved} inputs, how is it possible to learn in any
meaningful sense?
<p>
<!-- !split -->
<h2 id="___sec94">Training and testing data </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{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model
$$
y=f(\boldsymbol{x}) + \epsilon
$$
where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec95">Procedure to find a predictor </h2>
<p>
We have a statistical procedure (e.g. least-squares regression) for
forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the
prediction of our model for a new data point \( \boldsymbol{x} \). This estimator
is chosen by minimizing a cost function which we take to be the
squared error
$$
\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec96">What we want </h2>
<p>
We are interested in the generalization error on all data drawn from
the true model, not just the error on the particular training dataset
\( \mathcal{L} \) that we have in hand. This is just the expectation of
the cost function over many different data sets
\( \{\mathcal{L}_j\} \). Denote this expectation value by
\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \)
as a stochastic functional that depends on the dataset \( \mathcal{L} \)
and we can think of \( E_{\mathcal{L}} \) as the expected value of the
functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,
\mathcal{L}_2, \ldots \} \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec97">The expected generalization error </h2>
<p>
We would also like to average over different instances of the
&quot;noise&quot; \( \epsilon \) and we denote the expectation value over the
noise by \( E_\epsilon \). Thus, we can decompose the expected
generalization error as
$$
\begin{align}
E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\
&= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\
&= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\
&=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2],
\label{_auto17}
\end{align}
$$
<p>
where in the last line we used the fact that our noise has zero mean
and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all
terms.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec98">Elaborating a little bit more </h2>
<p>
It is also helpful to further decompose the second term as
follows:
$$
\begin{align}
E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\
&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\
&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\
&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2].
\label{_auto18}
\end{align}
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec99">The bias </h2>
<p>
The first term is called the bias
$$
Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2
$$
and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec100">The variance </h2>
The second term is called the variance
$$
Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2],
$$
<p>
and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as
$$
E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise.
$$
<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 &ndash; a model whose asymptotic
performance is worse than another model &ndash; because it is easier to
train and less sensitive to sampling noise arising from having a
finite-sized training dataset (smaller variance).
<p>
<!-- !split -->
<h2 id="___sec101">Summing up </h2>
<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>
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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec102">The one-dimensional Ising model, project 2 </h2>
<p>
The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by
$$
\begin{align}
H = -J \sum_{k}^L s_k s_{k + 1},
\label{_auto19}
\end{align}
$$
where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the low temperature limit there is no phase transition.
<p>
We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>L <span style="color: #666666">=</span> <span style="color: #666666">40</span>
n <span style="color: #666666">=</span> <span style="color: #008000">int</span>(<span style="color: #666666">1e4</span>)
spins <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice([<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>], size<span style="color: #666666">=</span>(n, L))
J <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
energies <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
<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):
energies[i] <span style="color: #666666">=</span> <span style="color: #666666">-</span> J <span style="color: #666666">*</span> np<span style="color: #666666">.</span>dot(spins[i], np<span style="color: #666666">.</span>roll(spins[i], <span style="color: #666666">1</span>))
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec103">Example: The one-dimensional Ising model </h2>
<p>
Here we use linear (ordinary least squares), ridge and LASSO
regression to predict the energy in the nearest neighbor
one-dimensional Ising model on a ring, i.e., the endpoints wrap
around. We will use the linear regression models to fit a value for
the coupling constant to achieve this.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></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">mpl_toolkits.axes_grid1</span> <span style="color: #008000; font-weight: bold">import</span> make_axes_locatable
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scipy.linalg</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">scl</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> train_test_split
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skl</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tqdm</span>
sns<span style="color: #666666">.</span>set(color_codes<span style="color: #666666">=</span><span style="color: #008000">True</span>)
cmap_args<span style="color: #666666">=</span><span style="color: #008000">dict</span>(vmin<span style="color: #666666">=-1.</span>, vmax<span style="color: #666666">=1.</span>, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&#39;seismic&#39;</span>)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec104">Reformulating the problem to suit regression </h2>
<p>
A more general form for the one-dimensional Ising model is
$$
\begin{align}
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
\label{_auto20}
\end{align}
$$
<p>
Here we allow for interactions beyond the nearest neighbors and a more
adaptive coupling matrix. This latter expression can be formulated as
a matrix-product on the form
$$
\begin{align}
H = X J,
\label{_auto21}
\end{align}
$$
<p>
where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the
elements \( -J_{jk} \). This form of writing the energy fits perfectly
with the form utilized in linear regression, viz.
$$
\begin{align}
y = X\omega + \epsilon,
\label{_auto22}
\end{align}
$$
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n, L <span style="color: #666666">**</span> <span style="color: #666666">2</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>(n):
X[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>outer(spins[i], spins[i])<span style="color: #666666">.</span>ravel()
y <span style="color: #666666">=</span> energies
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.96</span>)
X_train_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_train))[:, np<span style="color: #666666">.</span>newaxis], X_train),
axis<span style="color: #666666">=1</span>
)
X_test_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_test))[:, np<span style="color: #666666">.</span>newaxis], X_test),
axis<span style="color: #666666">=1</span>
)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec105">Linear regression </h2>
<p>
The problem at hand is to try to fit the equation
$$
\begin{align}
y = f(x) + \epsilon,
\label{_auto23}
\end{align}
$$
<p>
where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \)
is normally distributed with mean zero noise with standard deviation
\( \sigma_{\epsilon} \). Our job is to try to find a predictor which
estimates the function \( f(x) \). In linear regression we assume that we
can formulate the problem as
$$
\begin{align}
y = X\omega + \epsilon,
\label{_auto24}
\end{align}
$$
<p>
where \( X \) and \( \omega \) are now matrices. Our job at hand is now to
find a <b>cost function</b> \( C \), which we wish to minimize in order to find
the best estimate of \( \omega \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec106">Ordinary least squares </h2>
<p>
In the ordinary least squares method we choose the cost function
$$
\begin{align}
C(X, \omega) = ||X\omega - y||^2
= (X\omega - y)^T(X\omega - y)
\label{_auto25}
\end{align}
$$
We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e.,
$$
\begin{align}
\dfrac{\mathrm{d}C}{\mathrm{d}\omega}
= 0.
\label{_auto26}
\end{align}
$$
This yields the expression for \( \omega \) to be
$$
\begin{align}
\omega = \frac{X^T y}{X^T X},
\label{_auto27}
\end{align}
$$
<p>
which immediately imposes some requirements on \( X \) as there must exist
an inverse of \( X^T X \). If the expression we are modelling contains an
intercept, i.e., a constant expression we must make sure that the
first column of \( X \) consists of \( 1 \).
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_ols_weights_naive</span>(x: np<span style="color: #666666">.</span>ndarray, y: np<span style="color: #666666">.</span>ndarray) <span style="color: #666666">-&gt;</span> np<span style="color: #666666">.</span>ndarray:
<span style="color: #008000; font-weight: bold">return</span> scl<span style="color: #666666">.</span>inv(x<span style="color: #666666">.</span>T @ x) @ (x<span style="color: #666666">.</span>T @ y)
omega <span style="color: #666666">=</span> get_ols_weights_naive(X_train_own, y_train)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec107">Singular Value decomposition </h2>
Doing the inversion directly turns out to be a bad idea as the matrix
\( X^TX \) is singular. An alternative approach is to use the <b>singular
value decomposition</b>. Using the definition of the Moore-Penrose
pseudoinverse we can write the equation for \( \omega \) as
$$
\begin{align}
\omega = X^{+}y,
\label{_auto28}
\end{align}
$$
where the pseudoinverse of \( X \) is given by
$$
\begin{align}
X^{+} = \frac{X^T}{X^T X}.
\label{_auto29}
\end{align}
$$
<p>
Using singular value decomposition we have that \( X = U\Sigma V^T \),
where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
\( \omega \) to
$$
\begin{align}
\omega = V\Sigma^{+} U^T y.
\label{_auto30}
\end{align}
$$
<p>
Note that solving this equation by actually doing the pseudoinverse
(which is what we will do) is not a good idea as this operation scales
as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
general matrix. Instead, doing \( QR \)-factorization and solving the
linear system as an equation would reduce this down to
\( \mathcal{O}(n^2) \) operations.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_ols_weights</span>(x: np<span style="color: #666666">.</span>ndarray, y: np<span style="color: #666666">.</span>ndarray) <span style="color: #666666">-&gt;</span> np<span style="color: #666666">.</span>ndarray:
u, s, v <span style="color: #666666">=</span> scl<span style="color: #666666">.</span>svd(x)
<span style="color: #008000; font-weight: bold">return</span> v<span style="color: #666666">.</span>T @ scl<span style="color: #666666">.</span>pinv(scl<span style="color: #666666">.</span>diagsvd(s, u<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], v<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>])) @ u<span style="color: #666666">.</span>T @ y
</pre></div>
<p>
Before passing in the data to the function we append a column with ones to the training data.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>omega <span style="color: #666666">=</span> get_ols_weights(X_train_own,y_train)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec108">Fitting with scikit-learn </h2>
<p>
Next we fit a <code>LinearRegression</code>-model from Scikit-learn for comparison.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>clf <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>LinearRegression()<span style="color: #666666">.</span>fit(X_train, y_train)
</pre></div>
<p>
Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>J_own <span style="color: #666666">=</span> omega[<span style="color: #666666">1</span>:]<span style="color: #666666">.</span>reshape(L, L)
J_sk <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
</pre></div>
<p>
A way of looking at the coefficients in \( J \) is to plot the matrices as images.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_own, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Home-made OLS&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_sk, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;LinearRegression from Scikit-learn&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
We can see that our model for the least squares method performes close
to the benchmark from Scikit-learn. It is interesting to note that OLS
considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
valid matrix elements for \( J \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec109">Ridge regression </h2>
<p>
Having explored the ordinary least squares we move on to ridge
regression. In ridge regression we include a <b>regularizer</b>. This
involves a new cost function which leads to a new estimate for the
weights \( \omega \). This results in a penalized regression problem. The
cost function is given by
$$
\begin{align}
C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2
= (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega.
\label{_auto31}
\end{align}
$$
Finding the extremum of this function yields the weights
$$
\begin{align}
\omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda},
\label{_auto32}
\end{align}
$$
<p>
where \( \omega_{\text{LS}} \) is the weights from ordinary least
squares. The last assumption assumes that \( X \) is orthogonal, which it
is not. We will therefore resort to solving the equation as it stands
on the left hand side.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_ridge_weights</span>(x: np<span style="color: #666666">.</span>ndarray, y: np<span style="color: #666666">.</span>ndarray, _lambda: <span style="color: #008000">float</span>) <span style="color: #666666">-&gt;</span> np<span style="color: #666666">.</span>ndarray:
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">.</span>T @ y @ scl<span style="color: #666666">.</span>inv(
x<span style="color: #666666">.</span>T @ x <span style="color: #666666">+</span> np<span style="color: #666666">.</span>eye(x<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>], x<span style="color: #666666">.</span>shape[<span style="color: #666666">1</span>]) <span style="color: #666666">*</span> _lambda
)
<span style="color: #008000; font-weight: bold">lambda</span> <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
omega_ridge <span style="color: #666666">=</span> get_ridge_weights(X_train_own, y_train, np<span style="color: #666666">.</span>array([_lambda]))
clf_ridge <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>Ridge(alpha<span style="color: #666666">=</span>_lambda)<span style="color: #666666">.</span>fit(X_train, y_train)
J_ridge_own <span style="color: #666666">=</span> omega_ridge[<span style="color: #666666">1</span>:]<span style="color: #666666">.</span>reshape(L, L)
J_ridge_sk <span style="color: #666666">=</span> clf_ridge<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_ridge_own, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Home-made ridge regression&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_ridge_sk, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Ridge from Scikit-learn&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec110">LASSO regression </h2>
<p>
In the <b>Least Absolute Shrinkage and Selection Operator</b> (LASSO)-method we get a third cost function.
$$
\begin{align}
C(X, \omega; \lambda) =
||X\omega - y||^2 + \lambda ||\omega||
= (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}.
\label{_auto33}
\end{align}
$$
Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>clf_lasso <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>Lasso(alpha<span style="color: #666666">=</span>_lambda)<span style="color: #666666">.</span>fit(X_train, y_train)
J_lasso_sk <span style="color: #666666">=</span> clf_lasso<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_lasso_sk, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Lasso from Scikit-learn&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
It is quite striking how LASSO breaks the symmetry of the coupling
constant as opposed to ridge and OLS. We get a sparse solution with
\( J_{j, j + 1} = -1 \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec111">Performance of the different models </h2>
<p>
In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by
$$
\begin{align}
R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2},
\label{_auto34}
\end{align}
$$
where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \).
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">r_squared</span>(y, y_hat):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y <span style="color: #666666">-</span> y_hat) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_hat)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
</pre></div>
<p>
This is the same metric used by Scikit-learn for their regression models when scoring.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>y_hat <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
r_test <span style="color: #666666">=</span> r_squared(y_test, y_hat)
sk_r_test <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>score(X_test, y_test)
<span style="color: #008000; font-weight: bold">assert</span> <span style="color: #008000">abs</span>(r_test <span style="color: #666666">-</span> sk_r_test) <span style="color: #666666">&lt;</span> <span style="color: #666666">1e-2</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec112">Performance as function of the regularization parameter </h2>
<p>
We see how the different models perform for a different set of values for \( \lambda \).
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">5</span>, <span style="color: #666666">10</span>)
train_errors <span style="color: #666666">=</span> {
<span style="color: #BA2121">&quot;ols_own&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ols_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ridge_own&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ridge_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;lasso_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size)
}
test_errors <span style="color: #666666">=</span> {
<span style="color: #BA2121">&quot;ols_own&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ols_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ridge_own&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;ridge_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
<span style="color: #BA2121">&quot;lasso_sk&quot;</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size)
}
plot_counter <span style="color: #666666">=</span> <span style="color: #666666">1</span>
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">32</span>, <span style="color: #666666">54</span>))
<span style="color: #008000; font-weight: bold">for</span> i, _lambda <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(tqdm<span style="color: #666666">.</span>tqdm(lambdas)):
omega <span style="color: #666666">=</span> get_ols_weights(X_train_own, y_train)
y_hat_train <span style="color: #666666">=</span> X_train_own @ omega
y_hat_test <span style="color: #666666">=</span> X_test_own @ omega
train_errors[<span style="color: #BA2121">&quot;ols_own&quot;</span>][i] <span style="color: #666666">=</span> r_squared(y_train, y_hat_train)
test_errors[<span style="color: #BA2121">&quot;ols_own&quot;</span>][i] <span style="color: #666666">=</span> r_squared(y_test, y_hat_test)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">10</span>, <span style="color: #666666">5</span>, plot_counter)
plt<span style="color: #666666">.</span>imshow(omega[<span style="color: #666666">1</span>:]<span style="color: #666666">.</span>reshape(L, L), <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Home made OLS&quot;</span>)
plot_counter <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
omega <span style="color: #666666">=</span> get_ridge_weights(X_train_own, y_train, _lambda)
y_hat_train <span style="color: #666666">=</span> X_train_own @ omega
y_hat_test <span style="color: #666666">=</span> X_test_own @ omega
train_errors[<span style="color: #BA2121">&quot;ridge_own&quot;</span>][i] <span style="color: #666666">=</span> r_squared(y_train, y_hat_train)
test_errors[<span style="color: #BA2121">&quot;ridge_own&quot;</span>][i] <span style="color: #666666">=</span> r_squared(y_test, y_hat_test)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">10</span>, <span style="color: #666666">5</span>, plot_counter)
plt<span style="color: #666666">.</span>imshow(omega[<span style="color: #666666">1</span>:]<span style="color: #666666">.</span>reshape(L, L), <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&quot;Home made ridge, $\lambda = </span><span style="color: #BB6688; font-weight: bold">%.4f</span><span style="color: #BA2121">$&quot;</span> <span style="color: #666666">%</span> _lambda)
plot_counter <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
<span style="color: #008000; font-weight: bold">for</span> key, method <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">zip</span>(
[<span style="color: #BA2121">&quot;ols_sk&quot;</span>, <span style="color: #BA2121">&quot;ridge_sk&quot;</span>, <span style="color: #BA2121">&quot;lasso_sk&quot;</span>],
[skl<span style="color: #666666">.</span>LinearRegression(), skl<span style="color: #666666">.</span>Ridge(alpha<span style="color: #666666">=</span>_lambda), skl<span style="color: #666666">.</span>Lasso(alpha<span style="color: #666666">=</span>_lambda)]
):
method <span style="color: #666666">=</span> method<span style="color: #666666">.</span>fit(X_train, y_train)
train_errors[key][i] <span style="color: #666666">=</span> method<span style="color: #666666">.</span>score(X_train, y_train)
test_errors[key][i] <span style="color: #666666">=</span> method<span style="color: #666666">.</span>score(X_test, y_test)
omega <span style="color: #666666">=</span> method<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">10</span>, <span style="color: #666666">5</span>, plot_counter)
plt<span style="color: #666666">.</span>imshow(omega, <span style="color: #666666">**</span>cmap_args)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&quot;</span><span style="color: #BB6688; font-weight: bold">%s</span><span style="color: #BA2121">, $\lambda = </span><span style="color: #BB6688; font-weight: bold">%.4f</span><span style="color: #BA2121">$&quot;</span> <span style="color: #666666">%</span> (key, _lambda))
plot_counter <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
We can see that LASSO quite fast reaches a good solution for low
values of \( \lambda \), but will "wither" when we increase \( \lambda \) too
much. Ridge is more stable over a larger range of values for
\( \lambda \), but eventually also fades away.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec113">Finding the optimal value of \( \lambda \) </h2>
<p>
To determine which value of \( \lambda \) is best we plot the accuracy of
the models when predicting the training and the testing set. We expect
the accuracy of the training set to be quite good, but if the accuracy
of the testing set is much lower this tells us that we might be
subject to an overfit model. The ideal scenario is an accuracy on the
testing set that is close to the accuracy of the training set.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
colors <span style="color: #666666">=</span> {
<span style="color: #BA2121">&quot;ols_own&quot;</span>: <span style="color: #BA2121">&quot;b&quot;</span>,
<span style="color: #BA2121">&quot;ridge_own&quot;</span>: <span style="color: #BA2121">&quot;g&quot;</span>,
<span style="color: #BA2121">&quot;ols_sk&quot;</span>: <span style="color: #BA2121">&quot;r&quot;</span>,
<span style="color: #BA2121">&quot;ridge_sk&quot;</span>: <span style="color: #BA2121">&quot;y&quot;</span>,
<span style="color: #BA2121">&quot;lasso_sk&quot;</span>: <span style="color: #BA2121">&quot;c&quot;</span>
}
<span style="color: #008000; font-weight: bold">for</span> key <span style="color: #AA22FF; font-weight: bold">in</span> train_errors:
plt<span style="color: #666666">.</span>semilogx(
lambdas,
train_errors[key],
colors[key],
label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Train {0}&quot;</span><span style="color: #666666">.</span>format(key),
linewidth<span style="color: #666666">=4.0</span>
)
<span style="color: #008000; font-weight: bold">for</span> key <span style="color: #AA22FF; font-weight: bold">in</span> test_errors:
plt<span style="color: #666666">.</span>semilogx(
lambdas,
test_errors[key],
colors[key] <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;--&quot;</span>,
label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Test {0}&quot;</span><span style="color: #666666">.</span>format(key),
linewidth<span style="color: #666666">=4.0</span>
)
<span style="color: #408080; font-style: italic">#plt.semilogx(lambdas, train_errors[&quot;ols_own&quot;], label=&quot;Train (OLS own)&quot;)</span>
<span style="color: #408080; font-style: italic">#plt.semilogx(lambdas, test_errors[&quot;ols_own&quot;], label=&quot;Test (OLS own)&quot;)</span>
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;best&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$\lambda$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$R^2$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>tick_params(labelsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
From the above figure we can see that LASSO with \( \lambda = 10^{-2} \)
achieve a very good accuracy on the test set. This by far surpases the
other models for all values of \( \lambda \).
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>