531 lines
31 KiB
HTML
531 lines
31 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="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<meta name="description" content="Homework 1 Fall Semester 2020">
|
|
|
|
<title>Homework 1 Fall Semester 2020</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}
|
|
|
|
div { text-align: justify; text-justify: inter-word; }
|
|
</style>
|
|
|
|
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Exercise, Setting up various Python environments',
|
|
2,
|
|
None,
|
|
'___sec0'),
|
|
('Exercise 1: Our first Python encounter', 2, None, '___sec1'),
|
|
('Exercise 2: making your own data and exploring scikit-learn',
|
|
2,
|
|
None,
|
|
'___sec2'),
|
|
('Exercise 3: mean values and variances in linear regression',
|
|
2,
|
|
None,
|
|
'___sec3')]}
|
|
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>Homework 1 Fall Semester 2020</h1></center> <!-- document title -->
|
|
|
|
<p>
|
|
<!-- author(s): <a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_blank">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a> -->
|
|
|
|
<center>
|
|
<b><a href="http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" target="_blank">Data Analysis and Machine Learning FYS-STK3155/FYS4155</a></b>
|
|
</center>
|
|
|
|
<p>
|
|
<!-- institution -->
|
|
|
|
<center><b>Department of Physics, University of Oslo, Norway</b></center>
|
|
<br>
|
|
<p>
|
|
<center><h4>Aug 19, 2020</h4></center> <!-- date -->
|
|
<br>
|
|
|
|
<h2 id="___sec0">Exercise, Setting up various Python environments </h2>
|
|
|
|
<p>
|
|
The first exercise here is of a mere technical art. We want you to have
|
|
|
|
<ul>
|
|
<li> git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo <a href="https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html" target="_blank">GitHub facilities</a>.</li>
|
|
<li> Install various Python packages</li>
|
|
</ul>
|
|
|
|
We will make extensive use of Python as programming language and its
|
|
myriad of available libraries. You will find
|
|
IPython/Jupyter notebooks invaluable in your work. You can run <b>R</b>
|
|
codes in the Jupyter/IPython notebooks, with the immediate benefit of
|
|
visualizing your data. You can also use compiled languages like C++,
|
|
Rust, Fortran etc if you prefer. The focus in these lectures will be
|
|
on Python.
|
|
|
|
<p>
|
|
If you have Python installed (we recommend Python3) and you feel
|
|
pretty familiar with installing different packages, we recommend that
|
|
you install the following Python packages via <b>pip</b> as
|
|
|
|
<ol>
|
|
<li> pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow</li>
|
|
</ol>
|
|
|
|
For <b>Tensorflow</b>, we recommend following the instructions in the text of
|
|
<a href="http://shop.oreilly.com/product/0636920052289.do" target="_blank">Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly</a>
|
|
|
|
<p>
|
|
We will come back to <b>tensorflow</b> later.
|
|
|
|
<p>
|
|
For Python3, replace <b>pip</b> with <b>pip3</b>.
|
|
|
|
<p>
|
|
For OSX users we recommend, after having installed Xcode, to
|
|
install <b>brew</b>. Brew allows for a seamless installation of additional
|
|
software via for example
|
|
|
|
<ol>
|
|
<li> brew install python3</li>
|
|
</ol>
|
|
|
|
For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
|
|
you can use <b>pip</b> as well and simply install Python as
|
|
|
|
<ol>
|
|
<li> sudo apt-get install python3 (or python for Python2.7)</li>
|
|
</ol>
|
|
|
|
If you don't want to perform these operations separately and venture
|
|
into the hassle of exploring how to set up dependencies and paths, we
|
|
recommend two widely used distrubutions which set up all relevant
|
|
dependencies for Python, namely
|
|
|
|
<ul>
|
|
<li> <a href="https://docs.anaconda.com/" target="_blank">Anaconda</a>,</li>
|
|
</ul>
|
|
|
|
which is an open source
|
|
distribution of the Python and R programming languages for large-scale
|
|
data processing, predictive analytics, and scientific computing, that
|
|
aims to simplify package management and deployment. Package versions
|
|
are managed by the package management system <b>conda</b>.
|
|
|
|
<ul>
|
|
<li> <a href="https://www.enthought.com/product/canopy/" target="_blank">Enthought canopy</a></li>
|
|
</ul>
|
|
|
|
is a Python
|
|
distribution for scientific and analytic computing distribution and
|
|
analysis environment, available for free and under a commercial
|
|
license.
|
|
|
|
<p>
|
|
We recommend using <b>Anaconda</b>.
|
|
|
|
<p>
|
|
<!-- --- begin exercise --- -->
|
|
|
|
<h2 id="___sec1">Exercise 1: Our first Python encounter </h2>
|
|
|
|
<p>
|
|
This exercise has as its aim to write a small program which reads in data from a <b>csv</b> file on the equation of state for dense nuclear matter. The file is localized at <a href="https://github.com/mhjensen/MachineLearningMSU-FRIB2020/blob/master/doc/pub/Regression/ipynb/datafiles/EoS.csv" target="_blank"><tt>https://github.com/mhjensen/MachineLearningMSU-FRIB2020/blob/master/doc/pub/Regression/ipynb/datafiles/EoS.csv</tt></a>. Thereafter you will have to set up the design matrix \( \boldsymbol{X} \) for the \( n \)
|
|
datapoints and a polynomial of degree \( 3 \). The steps are:
|
|
|
|
<ul>
|
|
<li> Write a Python code which reads the in the above mentioned file.</li>
|
|
<li> Use for example <b>pandas</b> to order your data and find out how many data points there are.</li>
|
|
<li> Set thereafter up the design matrix with dimensionality \( n\times p \) where \( p=4 \) and where you have defined a polynomial of degree \( p-1=3 \). Print the matrix and check that the numbers are correct.</li>
|
|
</ul>
|
|
|
|
We recommend looking at the examples in the <a href="https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html" target="_blank">regression slides</a>.
|
|
|
|
<p>
|
|
<!-- --- begin solution of exercise --- -->
|
|
<b>Solution.</b>
|
|
<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">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
|
|
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">"Results"</span>
|
|
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"Results/FigureFiles"</span>
|
|
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"DataFiles/"</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
|
|
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
|
|
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
|
|
os<span style="color: #666666">.</span>makedirs(DATA_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
|
|
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
|
|
<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_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
|
|
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
|
|
|
|
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">"EoS.csv"</span>),<span style="color: #BA2121">'r'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Read the EoS data as csv file and organized into two arrays with density and energies</span>
|
|
EoS <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile, names<span style="color: #666666">=</span>(<span style="color: #BA2121">'Density'</span>, <span style="color: #BA2121">'Energy'</span>))
|
|
EoS[<span style="color: #BA2121">'Energy'</span>] <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>to_numeric(EoS[<span style="color: #BA2121">'Energy'</span>], errors<span style="color: #666666">=</span><span style="color: #BA2121">'coerce'</span>)
|
|
EoS <span style="color: #666666">=</span> EoS<span style="color: #666666">.</span>dropna()
|
|
Energies <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">'Energy'</span>]
|
|
Density <span style="color: #666666">=</span> EoS[<span style="color: #BA2121">'Density'</span>]
|
|
<span style="color: #408080; font-style: italic"># The design matrix now as function of various polytrops</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(Density),<span style="color: #666666">5</span>))
|
|
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> Density<span style="color: #666666">**</span>(<span style="color: #666666">2.0/3.0</span>)
|
|
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> Density
|
|
X[:,<span style="color: #666666">3</span>] <span style="color: #666666">=</span> Density<span style="color: #666666">**</span>(<span style="color: #666666">4.0/3.0</span>)
|
|
X[:,<span style="color: #666666">4</span>] <span style="color: #666666">=</span> Density<span style="color: #666666">**</span>(<span style="color: #666666">5.0/3.0</span>)
|
|
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, Energies, test_size<span style="color: #666666">=0.2</span>)
|
|
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
|
|
beta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytilde <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> beta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training R2"</span>)
|
|
<span style="color: #008000">print</span>(R2(y_train,ytilde))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training MSE"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_train,ytilde))
|
|
ypredict <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> beta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test R2"</span>)
|
|
<span style="color: #008000">print</span>(R2(y_test,ypredict))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test MSE"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_test,ypredict))
|
|
</pre></div>
|
|
<p>
|
|
<!-- --- end solution of exercise --- -->
|
|
|
|
<p>
|
|
<!-- --- end exercise --- -->
|
|
|
|
<p>
|
|
<!-- --- begin exercise --- -->
|
|
|
|
<h2 id="___sec2">Exercise 2: making your own data and exploring scikit-learn </h2>
|
|
|
|
<p>
|
|
We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \).
|
|
The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
|
|
<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>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+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</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>)
|
|
</pre></div>
|
|
<ol>
|
|
<li> Write your own code (following the examples under the <a href="https://compphysics.github.io/MachineLearningECT/doc/pub/Day1/html/Day1-bs.html" target="_blank">regression slides</a>) for computing the parametrization of the data set fitting a second-order polynomial.</li>
|
|
<li> Use thereafter <b>scikit-learn</b> (see again the examples in the regression slides) and compare with your own code.</li>
|
|
<li> Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as</li>
|
|
</ol>
|
|
|
|
$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
|
|
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
|
$$
|
|
|
|
and the \( R^2 \) score function.
|
|
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.
|
|
$$
|
|
|
|
You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions.
|
|
Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.
|
|
|
|
<p>
|
|
<!-- --- begin solution of exercise --- -->
|
|
<b>Solution.</b>
|
|
The code here is an example of where we define our own design matrix and fit parameters \( \beta \).
|
|
<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">os</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
|
|
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
|
|
<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_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
|
|
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
|
|
|
|
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>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># The design matrix now as function of a given polynomial</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),<span style="color: #666666">3</span>))
|
|
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
|
|
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> x
|
|
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> x<span style="color: #666666">**2</span>
|
|
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
|
|
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
|
|
beta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
|
|
<span style="color: #008000">print</span>(beta)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytilde <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> beta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training R2"</span>)
|
|
<span style="color: #008000">print</span>(R2(y_train,ytilde))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Training MSE"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_train,ytilde))
|
|
ypredict <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> beta
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test R2"</span>)
|
|
<span style="color: #008000">print</span>(R2(y_test,ypredict))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test MSE"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y_test,ypredict))
|
|
</pre></div>
|
|
<p>
|
|
<!-- --- end solution of exercise --- -->
|
|
|
|
<p>
|
|
<!-- --- end exercise --- -->
|
|
|
|
<p>
|
|
<!-- --- begin exercise --- -->
|
|
|
|
<h2 id="___sec3">Exercise 3: mean values and variances in linear regression </h2>
|
|
|
|
<p>
|
|
This exercise deals with various mean values ad variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of <a href="https://www.springer.com/gp/book/9780387848570" target="_blank">Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer</a>).
|
|
|
|
<p>
|
|
The assumption we have made is
|
|
that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
|
|
which describes our data
|
|
$$
|
|
\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
|
|
$$
|
|
|
|
<p>
|
|
We then approximate this function with our model from the solution of the linear regression equations (ordinary least squares OLS), that is our
|
|
function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we minimized \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), with
|
|
$$
|
|
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
|
|
$$
|
|
|
|
The matrix \( \boldsymbol{X} \) is the so-called design matrix.
|
|
|
|
<p>
|
|
<b>a)</b>
|
|
Show that the expectation value of \( \boldsymbol{y} \) for a given element \( i \)
|
|
$$
|
|
\begin{align*}
|
|
\mathbb{E}(y_i) & =\mathbf{X}_{i, \ast} \, \beta,
|
|
\end{align*}
|
|
$$
|
|
|
|
and that
|
|
its variance is
|
|
$$
|
|
\begin{align*} \mbox{Var}(y_i) & = \sigma^2.
|
|
\end{align*}
|
|
$$
|
|
|
|
Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
|
|
mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \).
|
|
|
|
<p>
|
|
<!-- --- begin solution of exercise --- -->
|
|
<b>Solution.</b>
|
|
We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)
|
|
$$
|
|
\begin{align*}
|
|
\mathbb{E}(y_i) & =
|
|
\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
|
|
\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
|
|
\end{align*}
|
|
$$
|
|
|
|
while
|
|
its variance is
|
|
$$
|
|
\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
|
|
- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
|
|
[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
|
|
\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
|
|
= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
|
|
\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
|
|
\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
|
|
\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
|
|
\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
|
|
\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
|
|
\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
|
|
\end{align*}
|
|
$$
|
|
|
|
Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
|
|
mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
|
|
|
|
<p>
|
|
<!-- --- end solution of exercise --- -->
|
|
|
|
<p>
|
|
<b>b)</b>
|
|
With the OLS expressions for the parameters \( \boldsymbol{\beta} \) show that
|
|
$$
|
|
\mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta}.
|
|
$$
|
|
|
|
<p>
|
|
<!-- --- begin solution of exercise --- -->
|
|
<b>Solution.</b>
|
|
$$
|
|
\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
|
|
$$
|
|
|
|
This means that the estimator of the regression parameters is unbiased.
|
|
|
|
<p>
|
|
<!-- --- end solution of exercise --- -->
|
|
|
|
<p>
|
|
<b>c)</b>
|
|
Show finally that the variance of \( \boldsymbol{\beta} \) is
|
|
$$
|
|
\begin{eqnarray*}
|
|
\mbox{Var}(\boldsymbol{\beta}) & = & \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}.
|
|
\end{eqnarray*}
|
|
$$
|
|
|
|
<p>
|
|
<!-- --- begin solution of exercise --- -->
|
|
<b>Solution.</b>
|
|
The variance of \( \boldsymbol{\beta} \) is
|
|
$$
|
|
\begin{eqnarray*}
|
|
\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
|
|
\\
|
|
& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
|
|
\\
|
|
% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
|
|
% \\
|
|
% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
|
|
% \\
|
|
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
|
|
\\
|
|
& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
|
|
% \\
|
|
% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
|
|
% \\
|
|
% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
|
|
\\
|
|
& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
|
|
\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
|
|
\end{eqnarray*}
|
|
$$
|
|
|
|
<p>
|
|
where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
|
|
\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
|
|
\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
|
|
\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
|
|
variance of the estimate of the \( j \)-th regression coefficient:
|
|
\( \boldsymbol{\sigma}^2 (\hat{\beta}_j ) = \boldsymbol{\sigma}^2 \sqrt{
|
|
[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to
|
|
construct a confidence interval for the estimates.
|
|
|
|
<p>
|
|
In a similar way, we can obtain analytical expressions for say the
|
|
expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
|
|
when we employ Ridge regression, allowing us again to define a confidence interval.
|
|
|
|
<p>
|
|
<!-- --- end solution of exercise --- -->
|
|
|
|
<p>
|
|
<!-- --- end exercise --- -->
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|