update on regression analysis

This commit is contained in:
mhjensen
2018-09-06 11:28:45 +02:00
parent eb9bc8a6ea
commit f5b9eb32a2
56 changed files with 9374 additions and 5675 deletions
+571 -154
View File
@@ -66,17 +66,14 @@ div { text-align: justify; text-justify: inter-word; }
<!-- tocinfo
{'highest level': 2,
'sections': [('Regression analysis, overarching aims', 2, None, '___sec0'),
('General linear models', 2, None, '___sec1'),
('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,
'___sec2'),
'___sec3'),
('Rewriting the fitting procedure as a linear algebra problem, '
'follows',
2,
None,
'___sec3'),
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'___sec4'),
@@ -84,12 +81,12 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'___sec5'),
('Optimizing our parameters', 2, None, '___sec6'),
('Optimizing our parameters, more details', 2, None, '___sec7'),
('Interpretations and optimizing our parameters',
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'___sec8'),
'___sec6'),
('Optimizing our parameters', 2, None, '___sec7'),
('Optimizing our parameters, more details', 2, None, '___sec8'),
('Interpretations and optimizing our parameters',
2,
None,
@@ -98,47 +95,71 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'___sec10'),
('The $\\chi^2$ function', 2, None, '___sec11'),
('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'),
('Simple regression model', 2, None, '___sec17'),
('The $\\chi^2$ function', 2, None, '___sec17'),
('Simple regression model', 2, None, '___sec18'),
('Simple regression model, now using _scikit-learn_',
2,
None,
'___sec18'),
'___sec19'),
('Simple linear regression model using _scikit-learn_',
2,
None,
'___sec19'),
('Simple linear regression model', 2, None, '___sec20'),
('Less noise', 2, None, '___sec21'),
('How to study our fits', 2, None, '___sec22'),
('Minimizing the cost function', 2, None, '___sec23'),
('Relative error', 2, None, '___sec24'),
('The richness of _scikit-learn_', 2, None, '___sec25'),
('Functions in _scikit-learn_', 2, None, '___sec26'),
('Other functions in _scikit-learn_', 2, None, '___sec27'),
'___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,
'___sec28'),
('Cubic polynomial in _scikit-learn_', 2, None, '___sec29'),
('Simple regression model with gradient descent',
'___sec29'),
('Cubic polynomial in _scikit-learn_', 2, None, '___sec30'),
('Polynomial Regression', 2, None, '___sec31'),
('Linking the regression analysis with a statistical '
'interpretation',
2,
None,
'___sec30'),
('Simple regression model with stochastic gradient descent',
2,
None,
'___sec31'),
('Polynomial Regression', 2, None, '___sec32'),
('Ridge and Lasso Regression', 2, None, '___sec33'),
'___sec32'),
('Expectation value and variance', 2, None, '___sec33'),
('The singular value decompostion', 2, None, '___sec34'),
('Lasso and Ridge regression', 2, None, '___sec35'),
('Logistic regression', 2, None, '___sec36')]}
('Code examples for Ridge and Lasso Regression',
2,
None,
'___sec35'),
('From standard regression to Ridge regressions',
2,
None,
'___sec36'),
('Fixing the singularity', 2, None, '___sec37'),
('A second-order polynomial with Ridge and Lasso',
2,
None,
'___sec38'),
('Fitting vs. predicting when data is in the model class',
2,
None,
'___sec39'),
('Fitting versus predicting when data is not in the model class',
2,
None,
'___sec40'),
('The code', 2, None, '___sec41'),
('Generating test data', 2, None, '___sec42'),
('Lasso regression', 2, None, '___sec43'),
('Logistic regression', 2, None, '___sec44')]}
end of tocinfo -->
<body>
@@ -180,7 +201,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Aug 24, 2018</h4></center> <!-- date -->
<center><h4>Sep 6, 2018</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -210,7 +231,38 @@ A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \)
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec1">General linear models </h2>
<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>
@@ -231,7 +283,7 @@ where \( \epsilon_i \) is the error in our approximation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec2">Rewriting the fitting procedure as a linear algebra problem </h2>
<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>
@@ -251,7 +303,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec3">Rewriting the fitting procedure as a linear algebra problem, follows </h2>
<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>
@@ -292,7 +344,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec4">Generalizing the fitting procedure as a linear algebra problem </h2>
<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>
@@ -315,7 +367,7 @@ $$
<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>
<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>
@@ -343,7 +395,7 @@ The left-hand side of this equation forms know. Our error vector \( \hat{\epsilo
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec6">Optimizing our parameters </h2>
<h2 id="___sec7">Optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -365,7 +417,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec7">Optimizing our parameters, more details </h2>
<h2 id="___sec8">Optimizing our parameters, more details </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -389,7 +441,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec8">Interpretations and optimizing our parameters </h2>
<h2 id="___sec9">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -428,7 +480,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec9">Interpretations and optimizing our parameters </h2>
<h2 id="___sec10">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -454,7 +506,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec10">Interpretations and optimizing our parameters </h2>
<h2 id="___sec11">Interpretations and optimizing our parameters </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -482,7 +534,7 @@ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the r
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec11">The \( \chi^2 \) function </h2>
<h2 id="___sec12">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -505,7 +557,7 @@ where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec12">The \( \chi^2 \) function </h2>
<h2 id="___sec13">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -533,7 +585,7 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec13">The \( \chi^2 \) function </h2>
<h2 id="___sec14">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -559,7 +611,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec14">The \( \chi^2 \) function </h2>
<h2 id="___sec15">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -590,7 +642,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec15">The \( \chi^2 \) function </h2>
<h2 id="___sec16">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -614,7 +666,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec16">The \( \chi^2 \) function </h2>
<h2 id="___sec17">The \( \chi^2 \) function </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
@@ -660,7 +712,7 @@ This approach (different linear and non-linear regression) suffers often from bo
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec17">Simple regression model </h2>
<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>
@@ -700,7 +752,7 @@ We see that, as expected, a linear fit gives a seemingly (from the graph) good r
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec18">Simple regression model, now using <b>scikit-learn</b> </h2>
<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
@@ -731,7 +783,7 @@ plt<span style="color: #666666">.</span>show()
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec19">Simple linear regression model using <b>scikit-learn</b> </h2>
<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.
@@ -799,7 +851,7 @@ plt<span style="color: #666666">.</span>show()
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec20">Simple linear regression model </h2>
<h2 id="___sec21">Simple linear regression model </h2>
<p>
This example serves several aims. It allows us to demonstrate several
@@ -821,7 +873,7 @@ where \( x \) is defined as before.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec21">Less noise </h2>
<h2 id="___sec22">Less noise </h2>
<p>
Does the fit look better? Indeed, by
@@ -834,7 +886,7 @@ 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="___sec22">How to study our fits </h2>
<h2 id="___sec23">How to study our fits </h2>
<p>
We need more rigorous criteria in defining whether we have succeeded or
@@ -856,7 +908,7 @@ dimensionless.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec23">Minimizing the cost function </h2>
<h2 id="___sec24">Minimizing the cost function </h2>
<p>
Minimizing the cost function is a central aspect of
@@ -877,7 +929,7 @@ the \( \chi^2 \) function becomes smaller.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec24">Relative error </h2>
<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
@@ -917,7 +969,7 @@ relative error.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec25">The richness of <b>scikit-learn</b> </h2>
<h2 id="___sec26">The richness of <b>scikit-learn</b> </h2>
<p>
As mentioned above, <b>scikit-learn</b> has an impressive functionality.
@@ -962,7 +1014,7 @@ plt<span style="color: #666666">.</span>show()
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec26">Functions in <b>scikit-learn</b> </h2>
<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
@@ -979,7 +1031,7 @@ 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="___sec27">Other functions in <b>scikit-learn</b> </h2>
<h2 id="___sec28">Other functions in <b>scikit-learn</b> </h2>
<p>
The <b>r2score</b> function computes \( R^2 \), the coefficient of
@@ -1003,7 +1055,7 @@ $$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec28">The mean absolute error and other functions in <b>scikit-learn</b> </h2>
<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
@@ -1028,12 +1080,13 @@ years etc.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec29">Cubic polynomial in <b>scikit-learn</b> </h2>
<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.
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>
@@ -1070,82 +1123,12 @@ plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">print</span> (error(y))
</pre></div>
<p>
Similarly, using <b>R</b>, we can perform similar studies.
(more details on <b>R</b> will be inserted later).
Using <b>R</b>, we can perform similar studies.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec30">Simple regression model with gradient descent </h2>
Add info about the equations, play around with different learning rates
<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>
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]
theta_linreg <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)
<span style="color: #008000; font-weight: bold">print</span>(theta_linreg)
theta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)
eta <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
Niterations <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
m <span style="color: #666666">=</span> <span style="color: #666666">100</span>
<span style="color: #008000; font-weight: bold">for</span> <span style="color: #008000">iter</span> <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(Niterations):
gradients <span style="color: #666666">=</span> <span style="color: #666666">2.0/</span>m<span style="color: #666666">*</span>xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>dot(theta)<span style="color: #666666">-</span>y)
theta <span style="color: #666666">-=</span> eta<span style="color: #666666">*</span>gradients
<span style="color: #008000; font-weight: bold">print</span>(theta)
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)
ypredict2 <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(theta_linreg)
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(xnew, ypredict2, <span style="color: #BA2121">&quot;b-&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="___sec31">Simple regression model with stochastic gradient descent </h2>
Add info about the equations, play around with different learning rates
<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>
<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> SGDRegressor
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]
theta_linreg <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)
<span style="color: #008000; font-weight: bold">print</span>(theta_linreg)
sgdreg <span style="color: #666666">=</span> SGDRegressor(n_iter <span style="color: #666666">=</span> <span style="color: #666666">50</span>, penalty<span style="color: #666666">=</span><span style="color: #008000">None</span>, eta0<span style="color: #666666">=0.1</span>)
sgdreg<span style="color: #666666">.</span>fit(x,y<span style="color: #666666">.</span>ravel())
<span style="color: #008000; font-weight: bold">print</span>(sgdreg<span style="color: #666666">.</span>intercept_, sgdreg<span style="color: #666666">.</span>coef_)
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec32">Polynomial Regression </h2>
<h2 id="___sec31">Polynomial Regression </h2>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
@@ -1173,10 +1156,92 @@ plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#3
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">Ridge and Lasso Regression </h2>
<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">Code examples for Ridge and Lasso Regression </h2>
<p>
@@ -1257,38 +1322,390 @@ plt<span style="color: #666666">.</span>show()
<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>
How can we use the singular value decomposition to find the parameters \( \beta_j \)? More details will come. We first note that a general \( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal matrix \( \hat{\Sigma} \) of dimensionality \( n\times n \) and two orthognal matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality \( m \times n \) and the last dimensionality \( n\times n \). We have then
$$
\hat{A} = \hat{U}\hat{\Sigma}\hat{V}
$$
</div>
<h2 id="___sec36">From standard regression to Ridge regressions </h2>
<p>
Add codes and discuss this in connection with lasso and ridge, show example where the standard inversion of a matrix fails and where SVD comes to rescue
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="___sec35">Lasso and Ridge regression </h2>
<h2 id="___sec37">Fixing the singularity </h2>
<p>
Discuss the mathematics here
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="___sec36">Logistic regression </h2>
Add discussion about classification versus regression, show examples of more than two cases and why regression is not the best approach. Motivate for k-nearest neighbors
<h2 id="___sec38">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="___sec39">Fitting vs. predicting when data is in the model class </h2>
<p>
Add examples on classification problems
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="___sec40">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="___sec41">The code </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="___sec42">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()
<span style="color: #408080; font-style: italic">#Linear Filename</span>
<span style="color: #408080; font-style: italic">#filename_test=Title+&quot;pred-linear.pdf&quot;</span>
<span style="color: #408080; font-style: italic">#Tenth Order Filename</span>
<span style="color: #408080; font-style: italic">#filename_test=Title+&quot;pred-o10.pdf&quot;</span>
<span style="color: #408080; font-style: italic">#plt.savefig(filename_test)</span>
<span style="color: #408080; font-style: italic">#plt.ylim((-6,12))</span>
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec43">Lasso regression </h2>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec44">Logistic regression </h2>
<!-- ------------------- end of main content --------------- -->