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

829 lines
42 KiB
HTML

<!--
Automatically generated HTML file from DocOnce source
(https://github.com/hplgit/doconce/)
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
<meta name="description" content="Data Analysis and Machine Learning: Introduction and Representing data">
<title>Data Analysis and Machine Learning: Introduction and Representing data</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
/* pre style removed because it will interfer with pygments */
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('What is Machine Learning?', 2, None, '___sec0'),
('Types of Machine Learning', 2, None, '___sec1'),
('Different algorithms', 2, None, '___sec2'),
('Software and needed installations', 2, None, '___sec3'),
('Python installers', 2, None, '___sec4'),
('Installing R, C++, cython or Julia', 2, None, '___sec5'),
('Introduction to Jupyter notebook and available tools',
2,
None,
'___sec6'),
('Doing it in R', 2, None, '___sec7'),
('Representing data, overarching aims', 2, None, '___sec8'),
('Representing data, more examples', 2, None, '___sec9'),
('Binning of data', 2, None, '___sec10'),
('Adding model complexity: Predator-Prey model from ecology',
2,
None,
'___sec11'),
('Case study from Hudson bay', 2, None, '___sec12'),
('Hudson bay data', 2, None, '___sec13'),
('Plotting the data', 2, None, '___sec14'),
('Hares and lynx in Hudson bay from 1900 to 1920',
2,
None,
'___sec15'),
('Why now create a computer model for the hare and lynx '
'populations?',
2,
None,
'___sec16'),
('The traditional (top-down) approach', 2, None, '___sec17'),
("The ``new'' discrete bottom-up approach", 2, None, '___sec18'),
('Basic (computer-friendly) mathematics notation',
2,
None,
'___sec19'),
('Basic dynamics of the population of hares',
2,
None,
'___sec20'),
('Basic dynamics of the population of lynx', 2, None, '___sec21'),
('Evolution equations', 2, None, '___sec22'),
('Adapt the model to the Hudson Bay case', 2, None, '___sec23'),
('The program', 2, None, '___sec24'),
('The plot', 2, None, '___sec25')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center><h1>Data Analysis and Machine Learning: Introduction and Representing data</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>
<!-- institution(s) -->
<center>[1] <b>Department of Physics, University of Oslo</b></center>
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>Dec 1, 2017</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<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>
<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>
<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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> Linear regression and its variants</li>
<li> Decision tree algorithms, from simpler to more complex ones</li>
<li> Nearest neighbors models</li>
<li> Bayesian statistics</li>
<li> Support vector machines and finally various variants of</li>
<li> Artifical neural networks</li>
</ol>
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.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow</li>
</ol>
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>
<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 pyhton2.7)</li>
</ol>
etc etc.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> anaconda</li>
<li> Enthought canopy</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec6">Introduction to Jupyter notebook and available tools </h2>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec7">Doing it in R </h2>
Use the Hudson bay model to load data and make plot in R and with python
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec8">Representing data, overarching aims </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<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">scipy</span> <span style="color: #008000; font-weight: bold">import</span> sparse
<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">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
eye <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">4</span>)
<span style="color: #008000; font-weight: bold">print</span>(eye)
sparse_mtx <span style="color: #666666">=</span> sparse<span style="color: #666666">.</span>csr_matrix(eye)
<span style="color: #008000; font-weight: bold">print</span>(sparse_mtx)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-10</span>,<span style="color: #666666">10</span>,<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sin(x)
plt<span style="color: #666666">.</span>plot(x,y,marker<span style="color: #666666">=</span><span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>show()
data <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;Name&#39;</span>: [<span style="color: #BA2121">&quot;John&quot;</span>, <span style="color: #BA2121">&quot;Anna&quot;</span>, <span style="color: #BA2121">&quot;Peter&quot;</span>, <span style="color: #BA2121">&quot;Linda&quot;</span>], <span style="color: #BA2121">&#39;Location&#39;</span>: [<span style="color: #BA2121">&quot;Roma&quot;</span>, <span style="color: #BA2121">&quot;Napoli&quot;</span>, <span style="color: #BA2121">&quot;Torino&quot;</span>, <span style="color: #BA2121">&quot;Milano&quot;</span>], <span style="color: #BA2121">&#39;Age&#39;</span>:[<span style="color: #666666">51</span>, <span style="color: #666666">21</span>, <span style="color: #666666">34</span>, <span style="color: #666666">45</span>]}
data_pandas <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(data)
display(data_pandas)
</pre></div>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec9">Representing data, more examples </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<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">scipy</span> <span style="color: #008000; font-weight: bold">import</span> sparse
<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">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">mglearn</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">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
x, y <span style="color: #666666">=</span> mglearn<span style="color: #666666">.</span>datasets<span style="color: #666666">.</span>make_wave(n_samples<span style="color: #666666">=100</span>)
line <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-3</span>,<span style="color: #666666">3</span>,<span style="color: #666666">1000</span>,endpoint<span style="color: #666666">=</span><span style="color: #008000">False</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>)
reg <span style="color: #666666">=</span> DecisionTreeRegressor(min_samples_split<span style="color: #666666">=3</span>)<span style="color: #666666">.</span>fit(x,y)
plt<span style="color: #666666">.</span>plot(line, reg<span style="color: #666666">.</span>predict(line), label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;decision tree&quot;</span>)
regline <span style="color: #666666">=</span> LinearRegression()<span style="color: #666666">.</span>fit(x,y)
plt<span style="color: #666666">.</span>plot(line, regline<span style="color: #666666">.</span>predict(line), label<span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Linear Rgression&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec10">Binning of data </h2>
Use the Hudson bay model to load data and make plot in R and with python
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> The set up of a specific hypothesis combined with</li>
<li> the experimental methods needed (one can study existing data or perform experiments)</li>
<li> analyzing and interpreting the data and performing further experiments if needed</li>
<li> trying to extract general behaviors and extract eventual laws or patterns</li>
<li> develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments</li>
</ul>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> plotting the data</li>
<li> derive a simple model for the population dynamics</li>
<li> (fitting parameters in the model to the data)</li>
<li> using the model predict the evolution other predator-pray systems</li>
</ol>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec14">Plotting the data </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
<!-- code=python (!bc pypro) 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">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: #408080; font-style: italic"># Load in data file</span>
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>loadtxt(<span style="color: #BA2121">&#39;Hudson_Bay.dat&#39;</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">&#39;,&#39;</span>, skiprows<span style="color: #666666">=1</span>)
<span style="color: #408080; font-style: italic"># Make arrays containing x-axis and hares and lynx populations</span>
year <span style="color: #666666">=</span> data[:,<span style="color: #666666">0</span>]
hares <span style="color: #666666">=</span> data[:,<span style="color: #666666">1</span>]
lynx <span style="color: #666666">=</span> data[:,<span style="color: #666666">2</span>]
plt<span style="color: #666666">.</span>plot(year, hares ,<span style="color: #BA2121">&#39;b-+&#39;</span>, year, lynx, <span style="color: #BA2121">&#39;r-o&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">1900</span>,<span style="color: #666666">1920</span>,<span style="color: #666666">0</span>, <span style="color: #666666">100.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;Year&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;Numbers of hares and lynx &#39;</span>)
plt<span style="color: #666666">.</span>legend((<span style="color: #BA2121">&#39;Hares&#39;</span>,<span style="color: #BA2121">&#39;Lynx&#39;</span>), loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;upper right&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Population of hares and lynx from 1900-1920 (x1000)}&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">&#39;Hudson_Bay_data.pdf&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">&#39;Hudson_Bay_data.png&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
</div>
<p>
% if FORMAT != 'ipynb':
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<li> We see oscillations in the data</li>
<li> What causes cycles to slow or speed up?</li>
<li> What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?</li>
<li> With a model we can better <em>understand the data</em></li>
<li> More important: we can understand the ecology dynamics of
predator-pray populations</li>
</ul>
% endif
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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:
$$
\begin{align*}
\frac{dH}{dt} &= H(a - b L)\\
\frac{dL}{dt} &= - L(d - c H)
\end{align*}
$$
<p>
Here,
<ul>
<li> \( H \) is the number of preys</li>
<li> \( L \) the number of predators</li>
<li> \( a \), \( b \), \( d \), \( c \) are parameters</li>
</ul>
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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<p>
<!-- !bpop -->
<ul>
<li> 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>
<li> Where appropriate the students should do the experiment(s) needed to collect the data.</li>
<li> 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>
<li> Now we want to increase the understanding through modeling.</li>
<li> 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>
<!-- !epop -->
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec19">Basic (computer-friendly) mathematics notation </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<ul>
<li> Time points: \( t_0,t_1,\ldots,t_m \)</li>
<li> Uniform distribution of time points: \( t_n=n\Delta t \)</li>
<li> \( H^n \): population of hares at time \( t_n \)</li>
<li> \( L^n \): population of lynx at time \( t_n \)</li>
<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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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:
$$
\Delta H = a \Delta t H^n
$$
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:
$$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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
$$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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
$$ H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n $$
$$ L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n $$
<p>
Note:
<ul>
<li> These equations are ready to be implemented!</li>
<li> But to start, we need \( H^0 \) and \( L^0 \) <br />
(which we can get from the data)</li>
<li> We also need values for \( a \), \( b \), \( d \), \( c \)</li>
</ul>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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>
<p>
<ul>
<li> As always, models tend to be general - as here, applicable
to &quot;all&quot; predator-pray systems</li>
<li> The critical issue is whether the <em>interaction</em> between hares and lynx
is sufficiently well modeled by \( \hbox{const}HL \)</li>
<li> The parameters \( a \), \( b \), \( d \), and \( c \) must be
estimated from data</li>
<li> Measure time in years</li>
<li> \( t_0=1900 \), \( t_m=1920 \)</li>
</ul>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec24">The program </h2>
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
<!-- code=python (!bc pypro) 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">def</span> <span style="color: #0000FF">solver</span>(m, H0, L0, dt, a, b, c, d, t0):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;Solve the difference equations for H and L over m years</span>
<span style="color: #BA2121; font-style: italic"> with time step dt (measured in years.&quot;&quot;&quot;</span>
num_intervals <span style="color: #666666">=</span> <span style="color: #008000">int</span>(m<span style="color: #666666">/</span><span style="color: #008000">float</span>(dt))
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(t0, t0 <span style="color: #666666">+</span> m, num_intervals<span style="color: #666666">+1</span>)
H <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(t<span style="color: #666666">.</span>size)
L <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(t<span style="color: #666666">.</span>size)
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&#39;Init:&#39;</span>, H0, L0, dt
H[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> H0
L[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> L0
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">0</span>, <span style="color: #008000">len</span>(t)<span style="color: #666666">-1</span>):
H[n<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> H[n] <span style="color: #666666">+</span> a<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>H[n] <span style="color: #666666">-</span> b<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>H[n]<span style="color: #666666">*</span>L[n]
L[n<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> L[n] <span style="color: #666666">+</span> d<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>H[n]<span style="color: #666666">*</span>L[n] <span style="color: #666666">-</span> c<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>L[n]
<span style="color: #008000; font-weight: bold">return</span> H, L, t
<span style="color: #408080; font-style: italic"># Load in data file</span>
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>loadtxt(<span style="color: #BA2121">&#39;Hudson_Bay.csv&#39;</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">&#39;,&#39;</span>, skiprows<span style="color: #666666">=1</span>)
<span style="color: #408080; font-style: italic"># Make arrays containing x-axis and hares and lynx populations</span>
t_e <span style="color: #666666">=</span> data[:,<span style="color: #666666">0</span>]
H_e <span style="color: #666666">=</span> data[:,<span style="color: #666666">1</span>]
L_e <span style="color: #666666">=</span> data[:,<span style="color: #666666">2</span>]
<span style="color: #408080; font-style: italic"># Simulate using the model</span>
H, L, t <span style="color: #666666">=</span> solver(m<span style="color: #666666">=20</span>, H0<span style="color: #666666">=34.91</span>, L0<span style="color: #666666">=3.857</span>, dt<span style="color: #666666">=0.1</span>,
a<span style="color: #666666">=0.4807</span>, b<span style="color: #666666">=0.02482</span>, c<span style="color: #666666">=0.9272</span>, d<span style="color: #666666">=0.02756</span>,
t0<span style="color: #666666">=1900</span>)
<span style="color: #408080; font-style: italic"># Visualize simulations and data</span>
plt<span style="color: #666666">.</span>plot(t_e, H_e, <span style="color: #BA2121">&#39;b-+&#39;</span>, t_e, L_e, <span style="color: #BA2121">&#39;r-o&#39;</span>, t, H, <span style="color: #BA2121">&#39;m--&#39;</span>, t, L, <span style="color: #BA2121">&#39;k--&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Year&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;Numbers of hares and lynx&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">1900</span>, <span style="color: #666666">1920</span>, <span style="color: #666666">0</span>, <span style="color: #666666">140</span>])
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Population of hares and lynx 1900-1920 (x1000)&#39;</span>)
plt<span style="color: #666666">.</span>legend((<span style="color: #BA2121">&#39;H_e&#39;</span>, <span style="color: #BA2121">&#39;L_e&#39;</span>, <span style="color: #BA2121">&#39;H&#39;</span>, <span style="color: #BA2121">&#39;L&#39;</span>), loc<span style="color: #666666">=</span><span style="color: #BA2121">&#39;upper left&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">&#39;Hudson_Bay_sim.pdf&#39;</span>)
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">&#39;Hudson_Bay_sim.png&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
</div>
<p>
% if FORMAT != 'ipynb':
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<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
<p>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>