Files
FYS-STK4155/doc/pub/How2ReadData/html/How2ReadData-reveal.html
T
2017-12-01 22:54:29 +01:00

963 lines
42 KiB
HTML

\
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
<meta name="description" content="Data Analysis and Machine Learning: Introduction and Representing data">
<title>Data Analysis and Machine Learning: Introduction and Representing data</title>
<!-- reveal.js: http://lab.hakim.se/reveal-js/ -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="reveal.js/css/reveal.css">
<link rel="stylesheet" href="reveal.js/css/theme/beige.css" id="theme">
<!--
<link rel="stylesheet" href="reveal.js/css/reveal.css">
<link rel="stylesheet" href="reveal.js/css/theme/beige.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/beigesmall.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/solarized.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/serif.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/night.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/moon.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/simple.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/sky.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/darkgray.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/default.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/cbc.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/simula.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/black.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/white.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/league.css" id="theme">
-->
<!-- For syntax highlighting -->
<link rel="stylesheet" href="reveal.js/lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<style type="text/css">
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-size: 60%; font-style: italic; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.reveal .alert-text-small { font-size: 80%; }
.reveal .alert-text-large { font-size: 130%; }
.reveal .alert-text-normal { font-size: 90%; }
.reveal .alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:5px solid #bababa;
-webkit-border-radius: 14px; -moz-border-radius: 14px;
border-radius:14px;
background-position: 10px 10px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 30px; /* 55px; if icon */
}
.reveal .alert-block {padding-top:14px; padding-bottom:14px}
.reveal .alert-block > p, .alert-block > ul {margin-bottom:1em}
/*.reveal .alert li {margin-top: 1em}*/
.reveal .alert-block p+p {margin-top:5px}
/*.reveal .alert-notice { background-image: url(http://hplgit.github.io/doconce/bundled/html_images/small_gray_notice.png); }
.reveal .alert-summary { background-image:url(http://hplgit.github.io/doconce/bundled/html_images/small_gray_summary.png); }
.reveal .alert-warning { background-image: url(http://hplgit.github.io/doconce/bundled/html_images/small_gray_warning.png); }
.reveal .alert-question {background-image:url(http://hplgit.github.io/doconce/bundled/html_images/small_gray_question.png); } */
</style>
<!-- Styles for table layout of slides -->
<style type="text/css">
td.padding {
padding-top:20px;
padding-bottom:20px;
padding-right:50px;
padding-left:50px;
}
</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside the <div class="slides"> container
is displayed as a slide -->
<div class="slides">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<section>
<!-- ------------------- main content ---------------------- -->
<center><h1 style="text-align: center;">Data Analysis and Machine Learning: Introduction and Representing data</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>&nbsp;<br>
<!-- institution(s) -->
<center>[1] <b>Department of Physics, University of Oslo</b></center>
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>&nbsp;<br>
<center><h4>Dec 1, 2017</h4></center> <!-- date -->
<br>
<p>
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</section>
<section>
<h2 id="___sec0">What is Machine Learning? </h2>
<p>
Machine learning is the science of giving computers the ability to
learn without being explicitly programmed. The idea is that there
exist generic algorithms which can be used to find patterns in a broad
class of data sets without having to write code specifically for each
problem. The algorithm will build its own logic based on the data.
<p>
Machine learning is a subfield of computer science, and is closely
related to computational statistics. It evolved from the study of
pattern recognition in artificial intelligence (AI) research, and has
made contributions to AI tasks like computer vision, natural language
processing and speech recognition. It has also, especially in later
years, found applications in a wide variety of other areas, including
bioinformatics, economy, physics, finance and marketing.
</section>
<section>
<h2 id="___sec1">Types of Machine Learning </h2>
<p>
The approaches to machine learning are many, but are often split into two main categories.
In <em>supervised learning</em> we know the answer to a problem,
and let the computer deduce the logic behind it. On the other hand, <em>unsupervised learning</em>
is a method for finding patterns and relationship in data sets without any prior knowledge of the system.
Some authours also operate with a third category, namely <em>reinforcement learning</em>. This is a paradigm
of learning inspired by behavioural psychology, where learning is achieved by trial-and-error,
solely from rewards and punishment.
<p>
Another way to categorize machine learning tasks is to consider the desired output of a system.
Some of the most common tasks are:
<ul>
<p><li> Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.</li>
<p><li> Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.</li>
<p><li> Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.</li>
</ul>
</section>
<section>
<h2 id="___sec2">Different algorithms </h2>
In this course we will build our machine learning approach on a statistical foundation, with elements
from data analysis, stochastic processes etc before we proceed with the following machine learning algorithms
<ol>
<p><li> Linear regression and its variants</li>
<p><li> Decision tree algorithms, from simpler to more complex ones</li>
<p><li> Nearest neighbors models</li>
<p><li> Bayesian statistics</li>
<p><li> Support vector machines and finally various variants of</li>
<p><li> Artifical neural networks</li>
</ol>
<p>
Before we proceed however, there are several practicalities with data analysis and software tools we would
like to present. These tools will help us in our understanding of various machine learning algorithms.
<p>
Our emphasis here is on understanding the mathematical aspects of different algorithms, however, where possible
we will emphasize the importance of using available software.
</section>
<section>
<h2 id="___sec3">Software and needed installations </h2>
We will make intensive use of python as programming language and the myriad of available libraries.
Furthermore, 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.
<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>
<p><li> pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow</li>
</ol>
<p>
For Python3, replace <b>pip</b> with <b>pip3</b>.
<p>
For OSX users we recommend also, after having installed Xcode, to install <b>brew</b>. Brew allows
for a seamless installation of additional software via for example
<ol>
<p><li> brew install python3</li>
</ol>
<p>
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>
<p><li> sudo apt-get install python3 (or python for pyhton2.7)</li>
</ol>
<p>
etc etc.
</section>
<section>
<h2 id="___sec4">Python installers </h2>
If you don't want to perform these operations separately, we recommend two widely used distrubutions which set up
all relevant dependencies for Python, namely
<ol>
<p><li> anaconda</li>
<p><li> Enthought canopy</li>
</ol>
</section>
<section>
<h2 id="___sec5">Installing R, C++, cython or Julia </h2>
<p>
You will also find it convenient to utilize R. Say more about R.
Jupyter/Ipython notebook allows you run <b>R</b> code interactively in your browser. The software library <b>R</b> is
tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts.
<p>
For the C++ affecianodas, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language
interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for
either Python or C++ as programming languages.
<p>
To add more entropy, <b>cython</b> can also be used when running your notebooks. It means that Python with the Jupyter/IPython notebook
setup allows you to integrate widely popular softwares and tools for scientific computing. With its versatility,
including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook
can easily be converted into a nicely rendered <b>PDF</b> file or a Latex file for further processing.
<p>
This never ends,
<p>
If you se the light mark-up language <b>doconce</b> you can convert a standard ascii text file into various HTML
formats, ipython notebooks, latex files, pdf files etc.
</section>
<section>
<h2 id="___sec6">Introduction to Jupyter notebook and available tools </h2>
</section>
<section>
<h2 id="___sec7">Doing it in R </h2>
Use the Hudson bay model to load data and make plot in R and with python
</section>
<section>
<h2 id="___sec8">Representing data, overarching aims </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">scipy</span> <span style="color: #8B008B; font-weight: bold">import</span> sparse
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> display
eye = np.eye(<span style="color: #B452CD">4</span>)
<span style="color: #8B008B; font-weight: bold">print</span>(eye)
sparse_mtx = sparse.csr_matrix(eye)
<span style="color: #8B008B; font-weight: bold">print</span>(sparse_mtx)
x = np.linspace(-<span style="color: #B452CD">10</span>,<span style="color: #B452CD">10</span>,<span style="color: #B452CD">100</span>)
y = np.sin(x)
plt.plot(x,y,marker=<span style="color: #CD5555">&#39;x&#39;</span>)
plt.show()
data = {<span style="color: #CD5555">&#39;Name&#39;</span>: [<span style="color: #CD5555">&quot;John&quot;</span>, <span style="color: #CD5555">&quot;Anna&quot;</span>, <span style="color: #CD5555">&quot;Peter&quot;</span>, <span style="color: #CD5555">&quot;Linda&quot;</span>], <span style="color: #CD5555">&#39;Location&#39;</span>: [<span style="color: #CD5555">&quot;Roma&quot;</span>, <span style="color: #CD5555">&quot;Napoli&quot;</span>, <span style="color: #CD5555">&quot;Torino&quot;</span>, <span style="color: #CD5555">&quot;Milano&quot;</span>], <span style="color: #CD5555">&#39;Age&#39;</span>:[<span style="color: #B452CD">51</span>, <span style="color: #B452CD">21</span>, <span style="color: #B452CD">34</span>, <span style="color: #B452CD">45</span>]}
data_pandas = pd.DataFrame(data)
display(data_pandas)
</pre></div>
</div>
</section>
<section>
<h2 id="___sec9">Representing data, more examples </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">scipy</span> <span style="color: #8B008B; font-weight: bold">import</span> sparse
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> display
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">mglearn</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">sklearn</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LinearRegression
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeRegressor
x, y = mglearn.datasets.make_wave(n_samples=<span style="color: #B452CD">100</span>)
line = np.linspace(-<span style="color: #B452CD">3</span>,<span style="color: #B452CD">3</span>,<span style="color: #B452CD">1000</span>,endpoint=<span style="color: #658b00">False</span>).reshape(-<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>)
reg = DecisionTreeRegressor(min_samples_split=<span style="color: #B452CD">3</span>).fit(x,y)
plt.plot(line, reg.predict(line), label=<span style="color: #CD5555">&quot;decision tree&quot;</span>)
regline = LinearRegression().fit(x,y)
plt.plot(line, regline.predict(line), label= <span style="color: #CD5555">&quot;Linear Rgression&quot;</span>)
plt.show()
</pre></div>
</div>
</section>
<section>
<h2 id="___sec10">Binning of data </h2>
Use the Hudson bay model to load data and make plot in R and with python
</section>
<section>
<h2 id="___sec11">Adding model complexity: Predator-Prey model from ecology </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The population dynamics of a simple predator-prey system is a
classical example shown in many biology textbooks when ecological
systems are discussed. The system contains all elements of the
scientific method:
<ul>
<p><li> The set up of a specific hypothesis combined with</li>
<p><li> the experimental methods needed (one can study existing data or perform experiments)</li>
<p><li> analyzing and interpreting the data and performing further experiments if needed</li>
<p><li> trying to extract general behaviors and extract eventual laws or patterns</li>
<p><li> develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments</li>
</ul>
</div>
</section>
<section>
<h2 id="___sec12">Case study from Hudson bay </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why?
We shall demonstrate the scientific method by
<ol>
<p><li> plotting the data</li>
<p><li> derive a simple model for the population dynamics</li>
<p><li> (fitting parameters in the model to the data)</li>
<p><li> using the model predict the evolution other predator-pray systems</li>
</ol>
</div>
</section>
<section>
<h2 id="___sec13">Hudson bay data </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
% if FORMAT == 'ipynb':
Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle.
<p>
One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920.
% endif
<p>
<table border="1">
<thead>
<tr><th align="center">Year</th> <th align="center">Hares (x1000)</th> <th align="center">Lynx (x1000)</th> </tr>
</thead>
<tbody>
<tr><td align="left"> 1900 </td> <td align="right"> 30.0 </td> <td align="right"> 4.0 </td> </tr>
<tr><td align="left"> 1901 </td> <td align="right"> 47.2 </td> <td align="right"> 6.1 </td> </tr>
<tr><td align="left"> 1902 </td> <td align="right"> 70.2 </td> <td align="right"> 9.8 </td> </tr>
<tr><td align="left"> 1903 </td> <td align="right"> 77.4 </td> <td align="right"> 35.2 </td> </tr>
<tr><td align="left"> 1904 </td> <td align="right"> 36.3 </td> <td align="right"> 59.4 </td> </tr>
<tr><td align="left"> 1905 </td> <td align="right"> 20.6 </td> <td align="right"> 41.7 </td> </tr>
<tr><td align="left"> 1906 </td> <td align="right"> 18.1 </td> <td align="right"> 19.0 </td> </tr>
<tr><td align="left"> 1907 </td> <td align="right"> 21.4 </td> <td align="right"> 13.0 </td> </tr>
<tr><td align="left"> 1908 </td> <td align="right"> 22.0 </td> <td align="right"> 8.3 </td> </tr>
<tr><td align="left"> 1909 </td> <td align="right"> 25.4 </td> <td align="right"> 9.1 </td> </tr>
<tr><td align="left"> 1910 </td> <td align="right"> 27.1 </td> <td align="right"> 7.4 </td> </tr>
<tr><td align="left"> 1911 </td> <td align="right"> 40.3 </td> <td align="right"> 8.0 </td> </tr>
<tr><td align="left"> 1912 </td> <td align="right"> 57 </td> <td align="right"> 12.3 </td> </tr>
<tr><td align="left"> 1913 </td> <td align="right"> 76.6 </td> <td align="right"> 19.5 </td> </tr>
<tr><td align="left"> 1914 </td> <td align="right"> 52.3 </td> <td align="right"> 45.7 </td> </tr>
<tr><td align="left"> 1915 </td> <td align="right"> 19.5 </td> <td align="right"> 51.1 </td> </tr>
<tr><td align="left"> 1916 </td> <td align="right"> 11.2 </td> <td align="right"> 29.7 </td> </tr>
<tr><td align="left"> 1917 </td> <td align="right"> 7.6 </td> <td align="right"> 15.8 </td> </tr>
<tr><td align="left"> 1918 </td> <td align="right"> 14.6 </td> <td align="right"> 9.7 </td> </tr>
<tr><td align="left"> 1919 </td> <td align="right"> 16.2 </td> <td align="right"> 10.1 </td> </tr>
<tr><td align="left"> 1920 </td> <td align="right"> 24.7 </td> <td align="right"> 8.6 </td> </tr>
</tbody>
</table>
</div>
</section>
<section>
<h2 id="___sec14">Plotting the data </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<!-- code=python (!bc pypro) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">matplotlib</span> <span style="color: #8B008B; font-weight: bold">import</span> pyplot <span style="color: #8B008B; font-weight: bold">as</span> plt
<span style="color: #228B22"># Load in data file</span>
data = np.loadtxt(<span style="color: #CD5555">&#39;Hudson_Bay.dat&#39;</span>, delimiter=<span style="color: #CD5555">&#39;,&#39;</span>, skiprows=<span style="color: #B452CD">1</span>)
<span style="color: #228B22"># Make arrays containing x-axis and hares and lynx populations</span>
year = data[:,<span style="color: #B452CD">0</span>]
hares = data[:,<span style="color: #B452CD">1</span>]
lynx = data[:,<span style="color: #B452CD">2</span>]
plt.plot(year, hares ,<span style="color: #CD5555">&#39;b-+&#39;</span>, year, lynx, <span style="color: #CD5555">&#39;r-o&#39;</span>)
plt.axis([<span style="color: #B452CD">1900</span>,<span style="color: #B452CD">1920</span>,<span style="color: #B452CD">0</span>, <span style="color: #B452CD">100.0</span>])
plt.xlabel(<span style="color: #CD5555">r&#39;Year&#39;</span>)
plt.ylabel(<span style="color: #CD5555">r&#39;Numbers of hares and lynx &#39;</span>)
plt.legend((<span style="color: #CD5555">&#39;Hares&#39;</span>,<span style="color: #CD5555">&#39;Lynx&#39;</span>), loc=<span style="color: #CD5555">&#39;upper right&#39;</span>)
plt.title(<span style="color: #CD5555">r&#39;Population of hares and lynx from 1900-1920 (x1000)}&#39;</span>)
plt.savefig(<span style="color: #CD5555">&#39;Hudson_Bay_data.pdf&#39;</span>)
plt.savefig(<span style="color: #CD5555">&#39;Hudson_Bay_data.png&#39;</span>)
plt.show()
</pre></div>
</div>
<p>
% if FORMAT != 'ipynb':
</section>
<section>
<h2 id="___sec15">Hares and lynx in Hudson bay from 1900 to 1920 </h2>
<p>
<br /><br /><center><p><img src="fig/Hudson_Bay_data.png" align="bottom" width=700></p></center><br /><br />
% endif
</section>
<section>
<h2 id="___sec16">Why now create a computer model for the hare and lynx populations? </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
% if FORMAT == 'ipynb':
We see from the plot that there are indeed fluctuations.
We would like to create a mathematical model that explains these
population fluctuations. Ecologists have predicted that in a simple
predator-prey system that a rise in prey population is followed (with
a lag) by a rise in the predator population. When the predator
population is sufficiently high, then the prey population begins
dropping. After the prey population falls, then the predator
population falls, which allows the prey population to recover and
complete one cycle of this interaction. Thus, we see that
qualitatively oscillations occur. Can a mathematical model predict
this? What causes cycles to slow or speed up? What affects the
amplitude of the oscillation or do you expect to see the oscillations
damp to a stable equilibrium? The models tend to ignore factors like
climate and other complicating factors. How significant are these?
% else:
<ul>
<p><li> We see oscillations in the data</li>
<p><li> What causes cycles to slow or speed up?</li>
<p><li> What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?</li>
<p><li> With a model we can better <em>understand the data</em></li>
<p><li> More important: we can understand the ecology dynamics of
predator-pray populations</li>
</ul>
<p>
% endif
</div>
</section>
<section>
<h2 id="___sec17">The traditional (top-down) approach </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The classical way (in all books) is to present the Lotka-Volterra equations:
<p>&nbsp;<br>
$$
\begin{align*}
\frac{dH}{dt} &= H(a - b L)\\
\frac{dL}{dt} &= - L(d - c H)
\end{align*}
$$
<p>&nbsp;<br>
<p>
Here,
<ul>
<p><li> \( H \) is the number of preys</li>
<p><li> \( L \) the number of predators</li>
<p><li> \( a \), \( b \), \( d \), \( c \) are parameters</li>
</ul>
<p>
Most books quickly establish the model and then use considerable space on
discussing the qualitative properties of this <em>nonlinear system of
ODEs</em> (which cannot be solved)
</div>
</section>
<section>
<h2 id="___sec18">The &quot;new&quot; discrete bottom-up approach </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b>The bottom-up approach.</b>
<ul>
<p><li class="fragment"> Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.</li>
<p><li class="fragment"> Where appropriate the students should do the experiment(s) needed to collect the data.</li>
<p><li class="fragment"> The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.</li>
<p><li class="fragment"> Now we want to increase the understanding through modeling.</li>
<p><li class="fragment"> Most of the biology lies in the <em>derivation</em> of the model. We shall
focus on an intuitive discrete approach that leads to difference
equations that can be programmed <em>and solved</em> directly.</li>
</ul>
</div>
</section>
<section>
<h2 id="___sec19">Basic (computer-friendly) mathematics notation </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<ul>
<p><li> Time points: \( t_0,t_1,\ldots,t_m \)</li>
<p><li> Uniform distribution of time points: \( t_n=n\Delta t \)</li>
<p><li> \( H^n \): population of hares at time \( t_n \)</li>
<p><li> \( L^n \): population of lynx at time \( t_n \)</li>
<p><li> We want to model the changes in populations, \( \Delta H=H^{n+1}-H^n \)
and \( \Delta L=L^{n+1}-L^n \) during a general time interval \( [t_{n+1},t_n] \)
of length \( \Delta t=t_{n+1}-t_n \)</li>
</ul>
</div>
</section>
<section>
<h2 id="___sec20">Basic dynamics of the population of hares </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The population of hares evolves due to births and deaths exactly as a bacteria population:
<p>&nbsp;<br>
$$
\Delta H = a \Delta t H^n
$$
<p>&nbsp;<br>
However, hares have an additional loss in the population because
they are eaten by lynx.
All the hares and lynx can form
\( H\cdot L \) pairs in total. When such pairs meet during a time
interval \( \Delta t \), there is some
small probablity that the lynx will eat the hare.
So in fraction \( b\Delta t HL \), the lynx eat hares. This
loss of hares and must be accounted for:
subtracted in the equation for hares:
<p>&nbsp;<br>
$$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$
<p>&nbsp;<br>
</div>
</section>
<section>
<h2 id="___sec21">Basic dynamics of the population of lynx </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
We assume that the primary growth for the lynx population depends on sufficient food for raising lynx kittens, which implies an adequate source of nutrients from predation on hares. Thus, the growth of the lynx population does not only depend of how many lynx there are, but on how many hares they can eat.
In a time interval \( \Delta t HL \) hares and lynx can meet, and in a
fraction \( b\Delta t HL \) the lynx eats the hare. All of this does not
contribute to the growth of lynx, again just a fraction of
\( b\Delta t HL \) that we write as
\( d\Delta t HL \). In addition, lynx die just as in the population
dynamics with one isolated animal population, leading to a loss
\( -c\Delta t L \).
</div>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
The accounting of lynx then looks like
<p>&nbsp;<br>
$$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$
<p>&nbsp;<br>
</div>
</section>
<section>
<h2 id="___sec22">Evolution equations </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
By writing up the definition of \( \Delta H \) and \( \Delta L \), and putting
all assumed known terms \( H^n \) and \( L^n \) on the right-hand side, we have
<p>&nbsp;<br>
$$ H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n $$
<p>&nbsp;<br>
<p>&nbsp;<br>
$$ L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n $$
<p>&nbsp;<br>
<p>
Note:
<ul>
<p><li> These equations are ready to be implemented!</li>
<p><li> But to start, we need \( H^0 \) and \( L^0 \) <br />
(which we can get from the data)</li>
<p><li> We also need values for \( a \), \( b \), \( d \), \( c \)</li>
</ul>
</div>
</section>
<section>
<h2 id="___sec23">Adapt the model to the Hudson Bay case </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<ul>
<p><li> As always, models tend to be general - as here, applicable
to &quot;all&quot; predator-pray systems</li>
<p><li> The critical issue is whether the <em>interaction</em> between hares and lynx
is sufficiently well modeled by \( \hbox{const}HL \)</li>
<p><li> The parameters \( a \), \( b \), \( d \), and \( c \) must be
estimated from data</li>
<p><li> Measure time in years</li>
<p><li> \( t_0=1900 \), \( t_m=1920 \)</li>
</ul>
</div>
</section>
<section>
<h2 id="___sec24">The program </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<!-- code=python (!bc pypro) typeset with pygments style "perldoc" -->
<div class="highlight" style="background: #eeeedd"><pre style="font-size: 80%; line-height: 125%"><span></span><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">solver</span>(m, H0, L0, dt, a, b, c, d, t0):
<span style="color: #CD5555">&quot;&quot;&quot;Solve the difference equations for H and L over m years</span>
<span style="color: #CD5555"> with time step dt (measured in years.&quot;&quot;&quot;</span>
num_intervals = <span style="color: #658b00">int</span>(m/<span style="color: #658b00">float</span>(dt))
t = np.linspace(t0, t0 + m, num_intervals+<span style="color: #B452CD">1</span>)
H = np.zeros(t.size)
L = np.zeros(t.size)
<span style="color: #8B008B; font-weight: bold">print</span> <span style="color: #CD5555">&#39;Init:&#39;</span>, H0, L0, dt
H[<span style="color: #B452CD">0</span>] = H0
L[<span style="color: #B452CD">0</span>] = L0
<span style="color: #8B008B; font-weight: bold">for</span> n <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">0</span>, <span style="color: #658b00">len</span>(t)-<span style="color: #B452CD">1</span>):
H[n+<span style="color: #B452CD">1</span>] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]
L[n+<span style="color: #B452CD">1</span>] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]
<span style="color: #8B008B; font-weight: bold">return</span> H, L, t
<span style="color: #228B22"># Load in data file</span>
data = np.loadtxt(<span style="color: #CD5555">&#39;Hudson_Bay.csv&#39;</span>, delimiter=<span style="color: #CD5555">&#39;,&#39;</span>, skiprows=<span style="color: #B452CD">1</span>)
<span style="color: #228B22"># Make arrays containing x-axis and hares and lynx populations</span>
t_e = data[:,<span style="color: #B452CD">0</span>]
H_e = data[:,<span style="color: #B452CD">1</span>]
L_e = data[:,<span style="color: #B452CD">2</span>]
<span style="color: #228B22"># Simulate using the model</span>
H, L, t = solver(m=<span style="color: #B452CD">20</span>, H0=<span style="color: #B452CD">34.91</span>, L0=<span style="color: #B452CD">3.857</span>, dt=<span style="color: #B452CD">0.1</span>,
a=<span style="color: #B452CD">0.4807</span>, b=<span style="color: #B452CD">0.02482</span>, c=<span style="color: #B452CD">0.9272</span>, d=<span style="color: #B452CD">0.02756</span>,
t0=<span style="color: #B452CD">1900</span>)
<span style="color: #228B22"># Visualize simulations and data</span>
plt.plot(t_e, H_e, <span style="color: #CD5555">&#39;b-+&#39;</span>, t_e, L_e, <span style="color: #CD5555">&#39;r-o&#39;</span>, t, H, <span style="color: #CD5555">&#39;m--&#39;</span>, t, L, <span style="color: #CD5555">&#39;k--&#39;</span>)
plt.xlabel(<span style="color: #CD5555">&#39;Year&#39;</span>)
plt.ylabel(<span style="color: #CD5555">&#39;Numbers of hares and lynx&#39;</span>)
plt.axis([<span style="color: #B452CD">1900</span>, <span style="color: #B452CD">1920</span>, <span style="color: #B452CD">0</span>, <span style="color: #B452CD">140</span>])
plt.title(<span style="color: #CD5555">r&#39;Population of hares and lynx 1900-1920 (x1000)&#39;</span>)
plt.legend((<span style="color: #CD5555">&#39;H_e&#39;</span>, <span style="color: #CD5555">&#39;L_e&#39;</span>, <span style="color: #CD5555">&#39;H&#39;</span>, <span style="color: #CD5555">&#39;L&#39;</span>), loc=<span style="color: #CD5555">&#39;upper left&#39;</span>)
plt.savefig(<span style="color: #CD5555">&#39;Hudson_Bay_sim.pdf&#39;</span>)
plt.savefig(<span style="color: #CD5555">&#39;Hudson_Bay_sim.png&#39;</span>)
plt.show()
</pre></div>
</div>
<p>
% if FORMAT != 'ipynb':
</section>
<section>
<h2 id="___sec25">The plot </h2>
<p>
<br /><br /><center><p><img src="fig/Hudson_Bay_sim.png" align="bottom" width=700></p></center><br /><br />
<p>
% else:
If we perform a least-square fitting, we can find optimal values for the parameters \( a \), \( b \), \( d \), \( c \). The optimal parameters are \( a=0.4807 \), \( b=0.02482 \), \( d=0.9272 \) and \( c=0.02756 \). These parameters result in a slightly modified initial conditions, namely \( H(0) = 34.91 \) and \( L(0)=3.857 \). With these parameters we are now ready to solve the equations and plot these data together with the experimental values.
% endif
</section>
</div> <!-- class="slides" -->
</div> <!-- class="reveal" -->
<script src="reveal.js/lib/js/head.min.js"></script>
<script src="reveal.js/js/reveal.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
// Display navigation controls in the bottom right corner
controls: true,
// Display progress bar (below the horiz. slider)
progress: true,
// Display the page number of the current slide
slideNumber: true,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
//center: true,
center: false,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Transition style
transition: 'default', // default/cube/page/concave/zoom/linear/fade/none
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'default', // default/none/slide/concave/convex/zoom
// Number of slides away from the current that are visible
viewDistance: 3,
// Parallax background image
//parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
// Parallax background size
//parallaxBackgroundSize: '' // CSS syntax, e.g. "2100px 900px"
theme: Reveal.getQueryHash().theme, // available themes are in reveal.js/css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/none
});
Reveal.initialize({
dependencies: [
// Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/
{ src: 'reveal.js/lib/js/classList.js', condition: function() { return !document.body.classList; } },
// Interpret Markdown in <section> elements
{ src: 'reveal.js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'reveal.js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
// Syntax highlight for <code> elements
{ src: 'reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
// Zoom in and out with Alt+click
{ src: 'reveal.js/plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
// Speaker notes
{ src: 'reveal.js/plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } },
// Remote control your reveal.js presentation using a touch device
//{ src: 'reveal.js/plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } },
// MathJax
//{ src: 'reveal.js/plugin/math/math.js', async: true }
]
});
Reveal.initialize({
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions. Can be
// specified using percentage units.
width: 1170, // original: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.0
});
</script>
<!-- begin footer logo
<div style="position: absolute; bottom: 0px; left: 0; margin-left: 0px">
<img src="somelogo.png">
</div>
end footer logo -->
</body>
</html>