1634 lines
101 KiB
HTML
1634 lines
101 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>
|
|
|
|
<!-- Bootstrap style: bootstrap -->
|
|
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
|
|
<!-- not necessary
|
|
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
|
|
-->
|
|
|
|
<style type="text/css">
|
|
|
|
/* Add scrollbar to dropdown menus in bootstrap navigation bar */
|
|
.dropdown-menu {
|
|
height: auto;
|
|
max-height: 400px;
|
|
overflow-x: hidden;
|
|
}
|
|
|
|
/* Adds an invisible element before each target to offset for the navigation
|
|
bar */
|
|
.anchor::before {
|
|
content:"";
|
|
display:block;
|
|
height:50px; /* fixed header height for style bootstrap */
|
|
margin:-50px 0 0; /* negative fixed header height */
|
|
}
|
|
</style>
|
|
|
|
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Introduction', 2, None, '___sec0'),
|
|
('Learning outcomes', 2, None, '___sec1'),
|
|
('Types of Machine Learning', 2, None, '___sec2'),
|
|
('Software and needed installations', 2, None, '___sec3'),
|
|
('Python installers', 2, None, '___sec4'),
|
|
('Installing R, C++, cython or Julia', 2, None, '___sec5'),
|
|
('Installing R, C++, cython or Julia', 2, None, '___sec6'),
|
|
('Introduction to Jupyter notebook and available tools',
|
|
2,
|
|
None,
|
|
'___sec7'),
|
|
('Representing data, more examples', 2, None, '___sec8'),
|
|
('Simple regression model', 2, None, '___sec9'),
|
|
('Simple regression model, now using _scikit-learn_',
|
|
2,
|
|
None,
|
|
'___sec10'),
|
|
('Simple regression model with gradient descent',
|
|
2,
|
|
None,
|
|
'___sec11'),
|
|
('Simple regression model with stochastic gradient descent',
|
|
2,
|
|
None,
|
|
'___sec12'),
|
|
('Polynomial regression', 2, None, '___sec13'),
|
|
('Predator-Prey model from ecology', 2, None, '___sec14'),
|
|
('Case study from Hudson bay', 2, None, '___sec15'),
|
|
('Hudson bay data', 2, None, '___sec16'),
|
|
('Plotting the data', 2, None, '___sec17'),
|
|
('Hares and lynx in Hudson bay from 1900 to 1920',
|
|
2,
|
|
None,
|
|
'___sec18'),
|
|
('Why now create a computer model for the hare and lynx '
|
|
'populations?',
|
|
2,
|
|
None,
|
|
'___sec19'),
|
|
('The traditional (top-down) approach', 2, None, '___sec20'),
|
|
('Basic mathematics notation', 2, None, '___sec21'),
|
|
('Basic dynamics of the population of hares',
|
|
2,
|
|
None,
|
|
'___sec22'),
|
|
('Basic dynamics of the population of lynx', 2, None, '___sec23'),
|
|
('Evolution equations', 2, None, '___sec24'),
|
|
('Adapt the model to the Hudson Bay case', 2, None, '___sec25'),
|
|
('The program', 2, None, '___sec26'),
|
|
('The plot', 2, None, '___sec27'),
|
|
('Linear regression in Python', 2, None, '___sec28'),
|
|
('Linear Least squares in R', 2, None, '___sec29'),
|
|
('Non-Linear Least squares in R', 2, None, '___sec30'),
|
|
('Example: ecoli lab experiment', 2, None, '___sec31'),
|
|
('The program', 2, None, '___sec32'),
|
|
('The output', 2, None, '___sec33'),
|
|
('Parameter estimation', 2, None, '___sec34'),
|
|
('A program relevant for the biological problem',
|
|
2,
|
|
None,
|
|
'___sec35'),
|
|
('Simulating financial transcations', 2, None, '___sec36'),
|
|
('Simulation of Transactions', 3, None, '___sec37')]}
|
|
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>
|
|
|
|
|
|
|
|
|
|
<!-- Bootstrap navigation bar -->
|
|
<div class="navbar navbar-default navbar-fixed-top">
|
|
<div class="navbar-header">
|
|
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</button>
|
|
<a class="navbar-brand" href="How2ReadData-bs.html">Data Analysis and Machine Learning: Introduction and Representing data</a>
|
|
</div>
|
|
|
|
<div class="navbar-collapse collapse navbar-responsive-collapse">
|
|
<ul class="nav navbar-nav navbar-right">
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
<!-- navigation toc: --> <li><a href="#___sec0" style="font-size: 80%;"><b>Introduction</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec1" style="font-size: 80%;"><b>Learning outcomes</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec2" style="font-size: 80%;"><b>Types of Machine Learning</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec3" style="font-size: 80%;"><b>Software and needed installations</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec4" style="font-size: 80%;"><b>Python installers</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec5" style="font-size: 80%;"><b>Installing R, C++, cython or Julia</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec6" style="font-size: 80%;"><b>Installing R, C++, cython or Julia</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec7" style="font-size: 80%;"><b>Introduction to Jupyter notebook and available tools</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec8" style="font-size: 80%;"><b>Representing data, more examples</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec9" style="font-size: 80%;"><b>Simple regression model</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec10" style="font-size: 80%;"><b>Simple regression model, now using <b>scikit-learn</b></b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec11" style="font-size: 80%;"><b>Simple regression model with gradient descent</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec12" style="font-size: 80%;"><b>Simple regression model with stochastic gradient descent</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec13" style="font-size: 80%;"><b>Polynomial regression</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec14" style="font-size: 80%;"><b>Predator-Prey model from ecology</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec15" style="font-size: 80%;"><b>Case study from Hudson bay</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec16" style="font-size: 80%;"><b>Hudson bay data</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec17" style="font-size: 80%;"><b>Plotting the data</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec18" style="font-size: 80%;"><b>Hares and lynx in Hudson bay from 1900 to 1920</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec19" style="font-size: 80%;"><b>Why now create a computer model for the hare and lynx populations?</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec20" style="font-size: 80%;"><b>The traditional (top-down) approach</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec21" style="font-size: 80%;"><b>Basic mathematics notation</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec22" style="font-size: 80%;"><b>Basic dynamics of the population of hares</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec23" style="font-size: 80%;"><b>Basic dynamics of the population of lynx</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec24" style="font-size: 80%;"><b>Evolution equations</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec25" style="font-size: 80%;"><b>Adapt the model to the Hudson Bay case</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec26" style="font-size: 80%;"><b>The program</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec27" style="font-size: 80%;"><b>The plot</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec28" style="font-size: 80%;"><b>Linear regression in Python</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec29" style="font-size: 80%;"><b>Linear Least squares in R</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec30" style="font-size: 80%;"><b>Non-Linear Least squares in R</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec31" style="font-size: 80%;"><b>Example: ecoli lab experiment</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec32" style="font-size: 80%;"><b>The program</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec33" style="font-size: 80%;"><b>The output</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec34" style="font-size: 80%;"><b>Parameter estimation</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec35" style="font-size: 80%;"><b>A program relevant for the biological problem</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec36" style="font-size: 80%;"><b>Simulating financial transcations</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec37" style="font-size: 80%;"> Simulation of Transactions</a></li>
|
|
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</div> <!-- end of navigation bar -->
|
|
|
|
<div class="container">
|
|
|
|
<p> </p><p> </p><p> </p> <!-- add vertical space -->
|
|
|
|
<!-- ------------------- main content ---------------------- -->
|
|
|
|
|
|
|
|
<div class="jumbotron">
|
|
<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>May 11, 2018</h4></center> <!-- date -->
|
|
<br>
|
|
<p>
|
|
<!-- potential-jumbotron-button -->
|
|
</div> <!-- end jumbotron -->
|
|
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec0" class="anchor">Introduction </h2>
|
|
|
|
<p>
|
|
Statistics, data science and machine learning form important fields of
|
|
research in modern science. They describe how to learn and make
|
|
predictions from data, as well allowing us to extract important
|
|
correlations about physical process and the underlying laws of motion
|
|
in large data sets. The latter, big data sets, appear
|
|
frequently in essentially all disciplines, from the traditional Science,
|
|
Technology, Mathematics and Engineering fields to Life Science, Law, education research,
|
|
the Humanities and
|
|
the Social Sciences. It has become more and more common to see
|
|
research projects on big data in for example the Social
|
|
Sciences where extracting patterns from complicated survey data is one of many research directions.
|
|
Having a solid grasp of data analysis and machine learning
|
|
is thus becoming central to scientific computing in many
|
|
fields, and competences and skills within the fields of machine learning
|
|
and scientific computing are nowadays strongly requested by many
|
|
potential employers. The latter cannot be overstated, familiarity with
|
|
machine learning has almost become a prerequisite for many of the most
|
|
exciting employment opportunities, whether they are in bioinformatics,
|
|
life science, physics or finance, in the private or the public
|
|
sector. This author has had several students or met students who have
|
|
been hired recently based on their skills and competences in
|
|
scientific computing and data science, often with marginal knowledge
|
|
of machine learning.
|
|
|
|
<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.
|
|
Machine learning represents 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 an extremely rich field, in spite of its young age. The
|
|
increases we have seen during the last three decades in computational
|
|
capabilities have been followed by developments of methods and
|
|
techniques for analyzing and handling large date sets, relying heavily
|
|
on statistics, computer science and mathematics. The field is rather
|
|
new and developing rapidly. Popular software packages written in
|
|
Python for machine learning like <a href="http://scikit-learn.org/stable/" target="_self">Scikit-learn</a>, <a href="https://www.tensorflow.org/" target="_self">Tensorflow</a>,
|
|
<a href="http://pytorch.org/" target="_self">PyTorch</a> and <a href="https://keras.io/" target="_self">Keras</a>, all freely available at their respective GitHub sites,
|
|
encompass communities of developers in the thousands or more. And the number
|
|
of code developers and contributors keeps increasing. Not all the
|
|
algorithms and methods can be given a rigorous mathematical
|
|
justification, opening up thereby large rooms for experimenting
|
|
and trial and error and thereby exciting new developments.
|
|
However, a solid command of linear algebra, multivariate theory,
|
|
probability theory, statistical data analysis,
|
|
understanding errors and Monte Carlo methods are central elements in a proper understanding of many of
|
|
algorithms and methods we will discuss.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec1" class="anchor">Learning outcomes </h2>
|
|
|
|
<p>
|
|
These lectures aim at giving you an overview of central aspects of
|
|
statistical data analysis as well as some of the central algorithms
|
|
used in machine learning. We will introduce a variety of central
|
|
algorithms and methods essential for studies of data analysis and
|
|
machine learning.
|
|
|
|
<p>
|
|
Hands-on projects and experimenting with data and algorithms plays a central role in
|
|
these lectures, and our hope is, through the various
|
|
projects and exercies, to expose you to fundamental
|
|
research problems in these fields, with the aim to reproduce state of
|
|
the art scientific results. You will learn to develop and
|
|
structure large codes for studying these systems, get acquainted with
|
|
computing facilities and learn to handle large scientific projects. A
|
|
good scientific and ethical conduct is emphasized throughout the
|
|
course. More specifically, you will
|
|
|
|
<ol>
|
|
<li> learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;</li>
|
|
<li> be capable of extending the acquired knowledge to other systems and cases;</li>
|
|
<li> Have an understanding of central algorithms used in data analysis and machine learning;</li>
|
|
<li> Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;</li>
|
|
<li> Understand methods for regression and classification;</li>
|
|
<li> Learn about neural network, genetic algorithms and Boltzmann machines;</li>
|
|
<li> Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).</li>
|
|
</ol>
|
|
|
|
There are several topics we will cover here, spanning from a
|
|
statistical data analysis and its basic concepts such expectation
|
|
values, variance, covariance, correlation functions and errors, via
|
|
well-known probability distribution functions like uniform
|
|
distribution, the binomial distribution, the Poisson distribution and
|
|
simple and multivariate normal distributions to central elements of
|
|
Bayesian statistics and modeling. We will also remind the reader about
|
|
central elements from linear algebra and standard methods based on
|
|
linear algebra used to fit functions such Cubic splines and gradient
|
|
methods for data optimization and the Singular-value decomposition and
|
|
least square methods for parameterizing data.
|
|
|
|
<p>
|
|
We will also cover Monte Carlo methods, Markov chains, well-known
|
|
algorithms for sampling stochastic events like the Metropolis-Hastings
|
|
and Gibbs sampling methods. An important aspect of all our
|
|
calculations is a proper estimation of errors. Here we will also
|
|
discuss famous resampling techniques like the blocking, bootstrapping
|
|
and jackknife methods.
|
|
|
|
<p>
|
|
The second part of the material covers several algorithms used in
|
|
machine learning.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec2" class="anchor">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 behavioral 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>
|
|
|
|
The methods we cover have three main topics in common, irrespective of
|
|
whether we deal with supervised or unsupervised learning. The first
|
|
ingredient is normally our data set, the second is a model which is
|
|
normally a function of some parameters. The last ingredient is a
|
|
so-called <b>cost</b> function which allows us to present an estimate on
|
|
how good our model is in reproducing the data it is supposed to train.
|
|
|
|
<p>
|
|
Here we will build our machine learning approach on elements of the
|
|
statistical foundation discussed above, with elements from data
|
|
analysis, stochastic processes etc. We will discuss the following
|
|
machine learning algorithms
|
|
|
|
<ol>
|
|
<li> Linear regression and its variants, in essence polynomial regression</li>
|
|
<li> Decision tree algorithms, from simpler to more complex ones</li>
|
|
<li> Nearest neighbors models</li>
|
|
<li> Bayesian statistics and regression</li>
|
|
<li> Support vector machines and finally various variants of</li>
|
|
<li> Artifical neural networks and deep learning</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. We start thus with a hands-on
|
|
and top-down approach machine learning. The aim is thus to start with
|
|
relevant data and use these to introduce statistical data analysis
|
|
concepts and machine learning algorithms before we delve into the
|
|
algorithms themselves. The examples we will use start with a simple
|
|
third-order polynomial with random noise added, and using the Python
|
|
software package <a href="http://scikit-learn.org/stable/" target="_self">Scikit-learn</a> we
|
|
will introduce various machine learning algorithm s to make fits of
|
|
the data data and predictions. We move thereafter to more interesting
|
|
cases such as the simulation of financial transactions or disease
|
|
models. These are examples where we can easily set up the data and
|
|
then use machine learning algorithms using included in for example <b>scikit-learn</b>. Another model we
|
|
will consider is the so-called Ising model. Here we will use this
|
|
model to produce data for selected spin configurations and attempt to classify the data.
|
|
Finally, our last example consists of economic data from the OECD.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec3" class="anchor">Software and needed installations </h2>
|
|
|
|
<p>
|
|
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 -->
|
|
|
|
<h2 id="___sec4" class="anchor">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> <a href="https://docs.anaconda.com/" target="_self">Anaconda</a> Anaconda 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></li>
|
|
<li> <a href="https://www.enthought.com/product/canopy/" target="_self">Enthought canopy</a> is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.</li>
|
|
</ol>
|
|
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec5" class="anchor">Installing R, C++, cython or Julia </h2>
|
|
|
|
<p>
|
|
You will also find it convenient to utilize 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>
|
|
To install <b>R</b> with Jupyter notebook <a href="https://mpacer.org/maths/r-kernel-for-ipython-notebook" target="_self">following the link here</a>
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec6" class="anchor">Installing R, C++, cython or Julia </h2>
|
|
|
|
<p>
|
|
For the C++ aficionados, 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. For example, convert to latex as
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>jupyter nbconvert filename<span style="color: #666666">.</span>ipynb <span style="color: #666666">--</span>to latex
|
|
</pre></div>
|
|
<p>
|
|
If you use 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 -->
|
|
|
|
<h2 id="___sec7" class="anchor">Introduction to Jupyter notebook and available tools </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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">'x'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
data <span style="color: #666666">=</span> {<span style="color: #BA2121">'Name'</span>: [<span style="color: #BA2121">"John"</span>, <span style="color: #BA2121">"Anna"</span>, <span style="color: #BA2121">"Peter"</span>, <span style="color: #BA2121">"Linda"</span>], <span style="color: #BA2121">'Location'</span>: [<span style="color: #BA2121">"Nairobi"</span>, <span style="color: #BA2121">"Napoli"</span>, <span style="color: #BA2121">"London"</span>, <span style="color: #BA2121">"Buenos Aires"</span>], <span style="color: #BA2121">'Age'</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>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec8" class="anchor">Representing data, more examples </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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">"decision tree"</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">"Linear Regression"</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec9" class="anchor">Simple regression model </h2>
|
|
Add info about the equations
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
|
|
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
|
|
xb <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)), x]
|
|
theta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb))<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>T)<span style="color: #666666">.</span>dot(y)
|
|
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
|
|
xbnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)), xnew]
|
|
ypredict <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(theta)
|
|
|
|
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">"r-"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">'ro'</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r'$x$'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'$y$'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Linear Regression'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec10" class="anchor">Simple regression model, now using <b>scikit-learn</b> </h2>
|
|
Add info about the equations
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
|
|
|
|
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
linreg <span style="color: #666666">=</span> LinearRegression()
|
|
linreg<span style="color: #666666">.</span>fit(x,y)
|
|
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
|
|
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(xnew)
|
|
|
|
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">"r-"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">'ro'</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r'$x$'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'$y$'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Random numbers '</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec11" class="anchor">Simple regression model with gradient descent </h2>
|
|
Add info about the equations, play around with different learning rates
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">math</span> <span style="color: #008000; font-weight: bold">import</span> exp, sqrt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
|
|
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
|
|
xb <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)), x]
|
|
theta_linreg <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb))<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>T)<span style="color: #666666">.</span>dot(y)
|
|
<span style="color: #008000; font-weight: bold">print</span>(theta_linreg)
|
|
theta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)
|
|
|
|
eta <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
|
|
Niterations <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
m <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> <span style="color: #008000">iter</span> <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(Niterations):
|
|
gradients <span style="color: #666666">=</span> <span style="color: #666666">2.0/</span>m<span style="color: #666666">*</span>xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>dot(theta)<span style="color: #666666">-</span>y)
|
|
theta <span style="color: #666666">-=</span> eta<span style="color: #666666">*</span>gradients
|
|
|
|
<span style="color: #008000; font-weight: bold">print</span>(theta)
|
|
xnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">0</span>],[<span style="color: #666666">2</span>]])
|
|
xbnew <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">2</span>,<span style="color: #666666">1</span>)), xnew]
|
|
ypredict <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(theta)
|
|
ypredict2 <span style="color: #666666">=</span> xbnew<span style="color: #666666">.</span>dot(theta_linreg)
|
|
plt<span style="color: #666666">.</span>plot(xnew, ypredict, <span style="color: #BA2121">"r-"</span>)
|
|
plt<span style="color: #666666">.</span>plot(xnew, ypredict2, <span style="color: #BA2121">"b-"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">'ro'</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">2.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">15.0</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r'$x$'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'$y$'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Random numbers '</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec12" class="anchor">Simple regression model with stochastic gradient descent </h2>
|
|
Add info about the equations, play around with different learning rates
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">math</span> <span style="color: #008000; font-weight: bold">import</span> exp, sqrt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">random</span> <span style="color: #008000; font-weight: bold">import</span> random, seed
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> SGDRegressor
|
|
|
|
x <span style="color: #666666">=</span> <span style="color: #666666">2*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
|
|
|
|
xb <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[np<span style="color: #666666">.</span>ones((<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)), x]
|
|
theta_linreg <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(xb<span style="color: #666666">.</span>T<span style="color: #666666">.</span>dot(xb))<span style="color: #666666">.</span>dot(xb<span style="color: #666666">.</span>T)<span style="color: #666666">.</span>dot(y)
|
|
<span style="color: #008000; font-weight: bold">print</span>(theta_linreg)
|
|
sgdreg <span style="color: #666666">=</span> SGDRegressor(n_iter <span style="color: #666666">=</span> <span style="color: #666666">50</span>, penalty<span style="color: #666666">=</span><span style="color: #008000">None</span>, eta0<span style="color: #666666">=0.1</span>)
|
|
sgdreg<span style="color: #666666">.</span>fit(x,y<span style="color: #666666">.</span>ravel())
|
|
<span style="color: #008000; font-weight: bold">print</span>(sgdreg<span style="color: #666666">.</span>intercept_, sgdreg<span style="color: #666666">.</span>coef_)
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec13" class="anchor">Polynomial regression </h2>
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec14" class="anchor">Predator-Prey model from ecology </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec15" class="anchor">Case study from Hudson bay </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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?
|
|
Here we start 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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec16" class="anchor">Hudson bay data </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
|
|
<p>
|
|
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.
|
|
|
|
<p>
|
|
|
|
<div class="row">
|
|
<div class="col-xs-3">
|
|
<table class="table table-striped table-hover table-condensed">
|
|
<thead>
|
|
<tr><td align="center"><b>Year</b></td> <td align="center"><b>Hares (x1000)</b></td> <td align="center"><b>Lynx (x1000)</b></td> </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> <!-- col-xs-3 -->
|
|
</div> <!-- cell row -->
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec17" class="anchor">Plotting the data </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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">'src/Hudson_Bay.csv'</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</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">'b-+'</span>, year, lynx, <span style="color: #BA2121">'r-o'</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'Year'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'Numbers of hares and lynx '</span>)
|
|
plt<span style="color: #666666">.</span>legend((<span style="color: #BA2121">'Hares'</span>,<span style="color: #BA2121">'Lynx'</span>), loc<span style="color: #666666">=</span><span style="color: #BA2121">'upper right'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Population of hares and lynx from 1900-1920 (x1000)}'</span>)
|
|
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">'Hudson_Bay_data.pdf'</span>)
|
|
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">'Hudson_Bay_data.png'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec18" class="anchor">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 />
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec19" class="anchor">Why now create a computer model for the hare and lynx populations? </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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?
|
|
|
|
<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>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec20" class="anchor">The traditional (top-down) approach </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec21" class="anchor">Basic mathematics notation </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
|
|
<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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec22" class="anchor">Basic dynamics of the population of hares </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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 must be accounted for. Subtracted in the equation for hares:
|
|
|
|
$$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec23" class="anchor">Basic dynamics of the population of lynx </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
The accounting of lynx then looks like
|
|
$$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec24" class="anchor">Evolution equations </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec25" class="anchor">Adapt the model to the Hudson Bay case </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
|
|
<ul>
|
|
<li> As always, models tend to be general - as here, applicable
|
|
to "all" 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>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec26" class="anchor">The program </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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">"""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."""</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">'Init:'</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">'src/Hudson_Bay.csv'</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</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">'b-+'</span>, t_e, L_e, <span style="color: #BA2121">'r-o'</span>, t, H, <span style="color: #BA2121">'m--'</span>, t, L, <span style="color: #BA2121">'k--'</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Year'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Numbers of hares and lynx'</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'Population of hares and lynx 1900-1920 (x1000)'</span>)
|
|
plt<span style="color: #666666">.</span>legend((<span style="color: #BA2121">'H_e'</span>, <span style="color: #BA2121">'L_e'</span>, <span style="color: #BA2121">'H'</span>, <span style="color: #BA2121">'L'</span>), loc<span style="color: #666666">=</span><span style="color: #BA2121">'upper left'</span>)
|
|
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">'Hudson_Bay_sim.pdf'</span>)
|
|
plt<span style="color: #666666">.</span>savefig(<span style="color: #BA2121">'Hudson_Bay_sim.png'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec27" class="anchor">The plot </h2>
|
|
|
|
<p>
|
|
<br /><br /><center><p><img src="fig/Hudson_Bay_sim.png" align="bottom" width=700></p></center><br /><br />
|
|
|
|
<p>
|
|
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.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec28" class="anchor">Linear regression in Python </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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">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">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
|
|
|
|
|
|
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>loadtxt(<span style="color: #BA2121">'src/Hudson_Bay.csv'</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</span>, skiprows<span style="color: #666666">=1</span>)
|
|
x <span style="color: #666666">=</span> data[:,<span style="color: #666666">0</span>]
|
|
y <span style="color: #666666">=</span> data[:,<span style="color: #666666">1</span>]
|
|
line <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">1900</span>,<span style="color: #666666">1920</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<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>),y<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
|
|
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">"decision tree"</span>)
|
|
regline <span style="color: #666666">=</span> LinearRegression()<span style="color: #666666">.</span>fit(x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>),y<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
|
|
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">"Linear Regression"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, y, label<span style="color: #666666">=</span> <span style="color: #BA2121">"Linear Regression"</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec29" class="anchor">Linear Least squares in R </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<p>
|
|
|
|
<!-- code=r (!bc r) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>HudsonBay <span style="color: #666666">=</span> read.csv(<span style="color: #BA2121">"src/Hudson_Bay.csv"</span>,header<span style="color: #666666">=</span><span style="color: #008000">T</span>)
|
|
fix(HudsonBay)
|
|
<span style="color: #008000">dim</span>(HudsonBay)
|
|
<span style="color: #008000">names</span>(HudsonBay)
|
|
plot(HudsonBay<span style="color: #666666">$</span>Year, HudsonBay<span style="color: #666666">$</span>Hares..x1000.)
|
|
<span style="color: #008000; font-weight: bold">attach</span>(HudsonBay)
|
|
plot(Year, Hares..x1000.)
|
|
plot(Year, Hares..x1000., col<span style="color: #666666">=</span><span style="color: #BA2121">"red"</span>, varwidth<span style="color: #666666">=</span><span style="color: #008000">T</span>, xlab<span style="color: #666666">=</span><span style="color: #BA2121">"Years"</span>, ylab<span style="color: #666666">=</span><span style="color: #BA2121">"Haresx 1000"</span>)
|
|
<span style="color: #008000">summary</span>(HudsonBay)
|
|
<span style="color: #008000">summary</span>(Hares..x1000.)
|
|
<span style="color: #008000; font-weight: bold">library</span>(MASS)
|
|
<span style="color: #008000; font-weight: bold">library</span>(ISLR)
|
|
scatter.smooth(x<span style="color: #666666">=</span>Year, y <span style="color: #666666">=</span> Hares..x1000.)
|
|
linearMod <span style="color: #666666">=</span> lm(Hares..x1000. <span style="color: #666666">~</span> Year)
|
|
<span style="color: #008000">print</span>(linearMod)
|
|
<span style="color: #008000">summary</span>(linearMod)
|
|
plot(linearMod)
|
|
confint(linearMod)
|
|
predict(linearMod,<span style="color: #B00040">data.frame</span>(Year<span style="color: #666666">=</span><span style="color: #B00040">c</span>(<span style="color: #666666">1910</span>,<span style="color: #666666">1914</span>,<span style="color: #666666">1920</span>)),interval<span style="color: #666666">=</span><span style="color: #BA2121">"confidence"</span>)
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec30" class="anchor">Non-Linear Least squares in R </h2>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<p>
|
|
|
|
<!-- code=r (!bc r) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000">set.seed</span>(<span style="color: #666666">1485</span>)
|
|
len <span style="color: #666666">=</span> <span style="color: #666666">24</span>
|
|
x <span style="color: #666666">=</span> runif(len)
|
|
y <span style="color: #666666">=</span> x<span style="color: #666666">^3+</span>rnorm(len, <span style="color: #666666">0</span>,<span style="color: #666666">0.06</span>)
|
|
ds <span style="color: #666666">=</span> <span style="color: #B00040">data.frame</span>(x <span style="color: #666666">=</span> x, y <span style="color: #666666">=</span> y)
|
|
str(ds)
|
|
plot( y <span style="color: #666666">~</span> x, main <span style="color: #666666">=</span><span style="color: #BA2121">"Known cubic with noise"</span>)
|
|
s <span style="color: #666666">=</span> <span style="color: #008000">seq</span>(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,length <span style="color: #666666">=100</span>)
|
|
lines(s, s<span style="color: #666666">^3</span>, lty <span style="color: #666666">=2</span>, col <span style="color: #666666">=</span><span style="color: #BA2121">"green"</span>)
|
|
m <span style="color: #666666">=</span> nls(y <span style="color: #666666">~</span> <span style="color: #008000">I</span>(x<span style="color: #666666">^</span>power), data <span style="color: #666666">=</span> ds, start <span style="color: #666666">=</span> <span style="color: #B00040">list</span>(power<span style="color: #666666">=1</span>), trace <span style="color: #666666">=</span> <span style="color: #008000">T</span>)
|
|
<span style="color: #008000">class</span>(m)
|
|
<span style="color: #008000">summary</span>(m)
|
|
power <span style="color: #666666">=</span> <span style="color: #008000">round</span>(<span style="color: #008000">summary</span>(m)<span style="color: #666666">$</span>coefficients[<span style="color: #666666">1</span>], <span style="color: #666666">3</span>)
|
|
power.se <span style="color: #666666">=</span> <span style="color: #008000">round</span>(<span style="color: #008000">summary</span>(m)<span style="color: #666666">$</span>coefficients[<span style="color: #666666">2</span>], <span style="color: #666666">3</span>)
|
|
plot(y <span style="color: #666666">~</span> x, main <span style="color: #666666">=</span> <span style="color: #BA2121">"Fitted power model"</span>, sub <span style="color: #666666">=</span> <span style="color: #BA2121">"Blue: fit; green: known"</span>)
|
|
s <span style="color: #666666">=</span> <span style="color: #008000">seq</span>(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, length <span style="color: #666666">=</span> <span style="color: #666666">100</span>)
|
|
lines(s, s<span style="color: #666666">^3</span>, lty <span style="color: #666666">=</span> <span style="color: #666666">2</span>, col <span style="color: #666666">=</span> <span style="color: #BA2121">"green"</span>)
|
|
lines(s, predict(m, <span style="color: #B00040">list</span>(x <span style="color: #666666">=</span> s)), lty <span style="color: #666666">=</span> <span style="color: #666666">1</span>, col <span style="color: #666666">=</span> <span style="color: #BA2121">"blue"</span>)
|
|
text(<span style="color: #666666">0</span>, <span style="color: #666666">0.5</span>, <span style="color: #008000">paste</span>(<span style="color: #BA2121">"y =x^ ("</span>, power, <span style="color: #BA2121">" +/- "</span>, power.se, <span style="color: #BA2121">")"</span>, sep <span style="color: #666666">=</span> <span style="color: #BA2121">""</span>), pos <span style="color: #666666">=</span> <span style="color: #666666">4</span>)
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec31" class="anchor">Example: ecoli lab experiment </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-primary">
|
|
<div class="panel-heading">
|
|
<h3 class="panel-title">Typical pattern:</h3>
|
|
</div>
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
The population grows faster and faster. <a href="http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html" target="_self">Why? Is there an underlying (general) mechanism</a>?
|
|
</div>
|
|
</div>
|
|
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
|
|
<ol>
|
|
<li> Cells divide after \( T \) seconds on average (one generation)</li>
|
|
<li> \( 2N \) celles divide into twice as many new cells \( \Delta N \) in a time
|
|
interval \( \Delta t \) as \( N \) cells would: \( \Delta N \propto N \)</li>
|
|
<li> \( N \) cells result in twice as many new individuals \( \Delta N \) in
|
|
time \( 2\Delta t \) as in time \( \Delta t \): \( \Delta N \propto\Delta t \)</li>
|
|
<li> Same proportionality wrt death (repeat reasoning)</li>
|
|
<li> Proposed model: \( \Delta N = b\Delta t N - d\Delta tN \) for some unknown
|
|
constants \( b \) (births) and \( d \) (deaths)</li>
|
|
<li> Describe evolution in discrete time: \( t_n=n\Delta t \)</li>
|
|
<li> Program-friendly notation: \( N \) at \( t_n \) is \( N^n \)</li>
|
|
<li> Math model: \( N^{n+1} = N^n + r\Delta t\, N \) (with \( \ r=b-d \))</li>
|
|
<li> Program model: <code>N[n+1] = N[n] + r*dt*N[n]</code></li>
|
|
</ol>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec32" class="anchor">The program </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
Let us solve the difference equation in as simple way as possible,
|
|
just to train some programming: \( r=1.5 \), \( N^0=1 \), \( \Delta t=0.5 \)
|
|
|
|
<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>
|
|
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">10</span>, <span style="color: #666666">21</span>) <span style="color: #408080; font-style: italic"># 20 intervals in [0, 10]</span>
|
|
dt <span style="color: #666666">=</span> t[<span style="color: #666666">1</span>] <span style="color: #666666">-</span> t[<span style="color: #666666">0</span>]
|
|
N <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(t<span style="color: #666666">.</span>size)
|
|
|
|
N[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
r <span style="color: #666666">=</span> <span style="color: #666666">0.5</span>
|
|
|
|
<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>, N<span style="color: #666666">.</span>size<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>):
|
|
N[n<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> N[n] <span style="color: #666666">+</span> r<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>N[n]
|
|
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">'N[</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">]=</span><span style="color: #BB6688; font-weight: bold">%.1f</span><span style="color: #BA2121">'</span> <span style="color: #666666">%</span> (n<span style="color: #666666">+1</span>, N[n<span style="color: #666666">+1</span>])
|
|
</pre></div>
|
|
<p>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
% if FORMAT != 'ipynb':
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec33" class="anchor">The output </h2>
|
|
|
|
<p>
|
|
|
|
<!-- code=text typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>N[1]=1.2
|
|
N[2]=1.6
|
|
N[3]=2.0
|
|
N[4]=2.4
|
|
N[5]=3.1
|
|
N[6]=3.8
|
|
N[7]=4.8
|
|
N[8]=6.0
|
|
N[9]=7.5
|
|
N[10]=9.3
|
|
N[11]=11.6
|
|
N[12]=14.6
|
|
N[13]=18.2
|
|
N[14]=22.7
|
|
N[15]=28.4
|
|
N[16]=35.5
|
|
N[17]=44.4
|
|
N[18]=55.5
|
|
N[19]=69.4
|
|
N[20]=86.7
|
|
</pre></div>
|
|
<p>
|
|
% endif
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec34" class="anchor">Parameter estimation </h2>
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
|
|
<ul>
|
|
<li> We do not know \( r \)</li>
|
|
<li> How can we estimate \( r \) from data?</li>
|
|
</ul>
|
|
|
|
We can use the difference equation with the experimental data
|
|
|
|
$$ N^{n+1} = N^n + r\Delta t N^n$$
|
|
|
|
Say \( N^{n+1} \) and \( N^n \) are known from data, solve wrt \( r \):
|
|
|
|
$$ r = \frac{N^{n+1}-N^n}{N^n\Delta t} $$
|
|
|
|
<p>
|
|
Use experimental data in the fraction, say \( t_1=600 \), \( t_2=1200 \),
|
|
\( N^1=140 \), \( N^2=250 \): \( r=0.0013 \).
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec35" class="anchor">A program relevant for the biological problem </h2>
|
|
|
|
<p>
|
|
<!-- exact r = 0.000694 -->
|
|
|
|
<p>
|
|
<div class="panel panel-default">
|
|
<div class="panel-body">
|
|
<p> <!-- subsequent paragraphs come in larger fonts, so start with a paragraph -->
|
|
<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: #408080; font-style: italic"># Estimate r</span>
|
|
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>loadtxt(<span style="color: #BA2121">'ecoli.csv'</span>, delimiter<span style="color: #666666">=</span><span style="color: #BA2121">','</span>)
|
|
t_e <span style="color: #666666">=</span> data[:,<span style="color: #666666">0</span>]
|
|
N_e <span style="color: #666666">=</span> data[:,<span style="color: #666666">1</span>]
|
|
i <span style="color: #666666">=</span> <span style="color: #666666">2</span> <span style="color: #408080; font-style: italic"># Data point (i,i+1) used to estimate r</span>
|
|
r <span style="color: #666666">=</span> (N_e[i<span style="color: #666666">+1</span>] <span style="color: #666666">-</span> N_e[i])<span style="color: #666666">/</span>(N_e[i]<span style="color: #666666">*</span>(t_e[i<span style="color: #666666">+1</span>] <span style="color: #666666">-</span> t_e[i]))
|
|
<span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">'Estimated r=</span><span style="color: #BB6688; font-weight: bold">%.5f</span><span style="color: #BA2121">'</span> <span style="color: #666666">%</span> r
|
|
<span style="color: #408080; font-style: italic"># Can experiment with r values and see if the model can</span>
|
|
<span style="color: #408080; font-style: italic"># match the data better</span>
|
|
|
|
T <span style="color: #666666">=</span> <span style="color: #666666">1200</span> <span style="color: #408080; font-style: italic"># cell can divide after T sec</span>
|
|
t_max <span style="color: #666666">=</span> <span style="color: #666666">5*</span>T <span style="color: #408080; font-style: italic"># 5 generations in experiment</span>
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, t_max, <span style="color: #666666">1000</span>)
|
|
dt <span style="color: #666666">=</span> t[<span style="color: #666666">1</span>] <span style="color: #666666">-</span> t[<span style="color: #666666">0</span>]
|
|
N <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(t<span style="color: #666666">.</span>size)
|
|
|
|
N[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
<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>, <span style="color: #666666">1</span>):
|
|
N[n<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> N[n] <span style="color: #666666">+</span> r<span style="color: #666666">*</span>dt<span style="color: #666666">*</span>N[n]
|
|
|
|
<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>
|
|
plt<span style="color: #666666">.</span>plot(t, N, <span style="color: #BA2121">'r-'</span>, t_e, N_e, <span style="color: #BA2121">'bo'</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'time [s]'</span>); plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'N'</span>)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'model'</span>, <span style="color: #BA2121">'experiment'</span>], loc<span style="color: #666666">=</span><span style="color: #BA2121">'upper left'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
Change <code>r</code> in the program and play around to make a better fit!
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec36" class="anchor">Simulating financial transcations </h2>
|
|
|
|
<p>
|
|
The aim here is to simulate financial transactions among financial agents
|
|
using Monte Carlo methods. The final goal is to extract a distribution of income as function
|
|
of the income \( m \). From Pareto's work (<a href="http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto" target="_self">V. Pareto, 1897</a>) it is known from empirical studies
|
|
that the higher end of the distribution of money follows a distribution
|
|
$$
|
|
w_m\propto m^{-1-\alpha},
|
|
$$
|
|
|
|
with \( \alpha\in [1,2] \). We will here follow the analysis made by <a href="http://www.sciencedirect.com/science/article/pii/S0378437104004327" target="_self">Patriarca and collaborators</a>.
|
|
|
|
<p>
|
|
Here we will study numerically the relation between the micro-dynamic relations among financial
|
|
agents and the resulting macroscopic money distribution.
|
|
|
|
<p>
|
|
We assume we have \( N \) agents that exchange money in pairs \( (i,j) \). We assume also that all agents
|
|
start with the same amount of money \( m_0 > 0 \). At a given 'time step', we choose randomly a pair
|
|
of agents \( (i,j) \) and let a transaction take place. This means that agent \( i \)'s money \( m_i \) changes
|
|
to \( m_i' \) and similarly we have \( m_j\rightarrow m_j' \).
|
|
Money is conserved during a transaction, meaning that
|
|
$$
|
|
\begin{equation}
|
|
m_i+m_j=m_i'+m_j'.
|
|
\label{eq:conserve}
|
|
\end{equation}
|
|
$$
|
|
|
|
The change is done via a random reassignement (a random number) \( \epsilon \), meaning that
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_i' = \epsilon(m_i+m_j),
|
|
\end{equation*}
|
|
$$
|
|
|
|
leading to
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_j'= (1-\epsilon)(m_i+m_j).
|
|
\end{equation*}
|
|
$$
|
|
|
|
The number \( \epsilon \) is extracted from a uniform distribution.
|
|
In this simple model, no agents are left with a debt, that is \( m\ge 0 \).
|
|
Due to the conservation law above, one can show that the system relaxes toward an equilibrium
|
|
state given by a Gibbs distribution
|
|
|
|
$$
|
|
\begin{equation*}
|
|
w_m=\beta \exp{(-\beta m)},
|
|
\end{equation*}
|
|
$$
|
|
|
|
with
|
|
|
|
$$
|
|
\begin{equation*}
|
|
\beta = \frac{1}{\langle m\rangle},
|
|
\end{equation*}
|
|
$$
|
|
|
|
and \( \langle m\rangle=\sum_i m_i/N=m_0 \), the average money.
|
|
It means that after equilibrium has been reached that the majority of agents is left with a small
|
|
number of money, while the number of richest agents, those with \( m \) larger than a specific value \( m' \),
|
|
exponentially decreases with \( m' \).
|
|
|
|
<p>
|
|
We assume that we have \( N=500 \) agents. In each simulation, we need a sufficiently large number of transactions, say \( 10^7 \). Our aim is find the final equilibrium distribution \( w_m \). In order to do that we would need
|
|
several runs of the above simulations, at least \( 10^3-10^4 \) runs (experiments).
|
|
|
|
<h3 id="___sec37" class="anchor">Simulation of Transactions </h3>
|
|
|
|
Our task is to first set up an algorithm which simulates the above transactions with an initial
|
|
amount \( m_0 \).
|
|
The challenge here is to figure out a Monte Carlo simulation based on the
|
|
above equations.
|
|
You will in particular need to make an algorithm which sets up a histogram as function of \( m \).
|
|
This histogram contains the number of times a value \( m \) is registered and represents
|
|
\( w_m\Delta m \). You will need to set up a value for the interval \( \Delta m \) (typically \( 0.01-0.05 \)).
|
|
That means you need to account for the number of times you register an income in the interval
|
|
\( m,m+\Delta m \). The number of times you register this income, represents the value that enters the histogram.
|
|
You will also need to find a criterion for when the equilibrium situation has been reached.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic">#!/usr/bin/env python</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.mlab</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">mlab</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">random</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># initialize the rng with a seed</span>
|
|
random<span style="color: #666666">.</span>seed()
|
|
<span style="color: #408080; font-style: italic"># Hard coding of input parameters</span>
|
|
Agents <span style="color: #666666">=</span> <span style="color: #666666">500</span>
|
|
MCcounts <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
Transactions <span style="color: #666666">=</span> <span style="color: #666666">100000</span>
|
|
startMoney <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
|
|
Lambda <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
|
|
FinancialAgents <span style="color: #666666">=</span> startMoney<span style="color: #666666">*</span>np<span style="color: #666666">.</span>ones(Agents)
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span> (<span style="color: #666666">1</span>, MCcounts, <span style="color: #666666">1</span>):
|
|
<span style="color: #008000; font-weight: bold">for</span> j <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span> (<span style="color: #666666">1</span>, Transactions, <span style="color: #666666">1</span>):
|
|
agent_i <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Agents<span style="color: #666666">*</span>random<span style="color: #666666">.</span>random())
|
|
agent_j <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Agents<span style="color: #666666">*</span>random<span style="color: #666666">.</span>random())
|
|
epsilon <span style="color: #666666">=</span> random<span style="color: #666666">.</span>random()
|
|
<span style="color: #008000; font-weight: bold">if</span> agent_i <span style="color: #666666">!=</span> agent_j:
|
|
m1 <span style="color: #666666">=</span> Lambda<span style="color: #666666">*</span>FinancialAgents[agent_i] <span style="color: #666666">+</span> (<span style="color: #666666">1-</span>Lambda)<span style="color: #666666">*</span>epsilon<span style="color: #666666">*</span>(FinancialAgents[agent_i] <span style="color: #666666">+</span> FinancialAgents[agent_j])
|
|
m2 <span style="color: #666666">=</span> Lambda<span style="color: #666666">*</span>FinancialAgents[agent_j] <span style="color: #666666">+</span> (<span style="color: #666666">1-</span>Lambda)<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>epsilon)<span style="color: #666666">*</span>(FinancialAgents[agent_i] <span style="color: #666666">+</span> FinancialAgents[agent_j])
|
|
FinancialAgents[agent_i] <span style="color: #666666">=</span> m1
|
|
FinancialAgents[agent_j] <span style="color: #666666">=</span> m2
|
|
|
|
<span style="color: #408080; font-style: italic"># the histogram of the data</span>
|
|
n, bins, patches <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>hist(FinancialAgents, <span style="color: #666666">50</span>, facecolor<span style="color: #666666">=</span><span style="color: #BA2121">'green'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'$x$'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'Distribution of wealth'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Money'</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">10</span>, <span style="color: #666666">0</span>, <span style="color: #666666">500</span>])
|
|
plt<span style="color: #666666">.</span>grid(<span style="color: #008000">True</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
We can then change our model to allow for a saving criterion, meaning that the agents save
|
|
a fraction \( \lambda \) of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions.
|
|
|
|
<p>
|
|
The conservation law of Eq. \eqref{eq:conserve} holds, but the money to be shared in a transaction between
|
|
agent \( i \) and agent \( j \) is now \( (1-\lambda)(m_i+m_j) \). This means that we have
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j),
|
|
\end{equation*}
|
|
$$
|
|
|
|
and
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j),
|
|
\end{equation*}
|
|
$$
|
|
|
|
which can be written as
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_i'=m_i+\delta m
|
|
\end{equation*}
|
|
$$
|
|
|
|
and
|
|
|
|
$$
|
|
\begin{equation*}
|
|
m_j'=m_j-\delta m,
|
|
\end{equation*}
|
|
$$
|
|
|
|
with
|
|
|
|
$$
|
|
\begin{equation*}
|
|
\delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i),
|
|
\end{equation*}
|
|
$$
|
|
|
|
showing how money is conserved during a transaction.
|
|
Select values of \( \lambda =0.25,0.5 \) and \( \lambda=0.9 \) and try to extract the corresponding
|
|
equilibrium distributions and compare these with the Gibbs distribution. Comment your results.
|
|
Extract a parametrization of the above curves, see for example <a href="http://www.sciencedirect.com/science/article/pii/S0378437104004327" target="_self">Patriarca and collaborators</a> and see if you can parametrize the high-end tails of the distributions in terms of power laws. Comment your results.
|
|
|
|
<p>
|
|
In the studies above the agents were selected randomly, irrespective of whether we allowed for
|
|
saving or not during a transaction. What is often observed is that various agents tend to make preferences for for whom to interact with. We will now study the evolution of the distribution of wealth \( w_m \) by assuming that there is a likelihood
|
|
$$
|
|
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha},
|
|
$$
|
|
|
|
for an interaction between agents \( i \) and \( j \) with respective wealths \( m_i \) and \( m_j \). The parameter \( \alpha > 0 \). For \( \alpha=0 \) we recover our model from part 5a).
|
|
Perform the same analysis as previously with \( N=500 \) as well as with \( N=1000 \) agents and study the distribution of wealth for \( \alpha =0.5 \), \( \alpha =1.0 \), \( \alpha =1.5 \) and \( \alpha =2.0 \).
|
|
You should try to reproduce Figure 1 of <a href="http://www.sciencedirect.com/science/article/pii/S0378437114006967" target="_self">Goswami and Sen</a>.
|
|
Extract the tail of the distribution and see if it follows a Pareto distribution
|
|
$$
|
|
w_m\propto m^{-1-\alpha}.
|
|
$$
|
|
|
|
What happens if \( \alpha \gg 1 \)?
|
|
|
|
<p>
|
|
Perform the analysis with and without a saving \( \lambda \) on each transaction and comment your results.
|
|
We add to the previous probability the possibility that two agents who interact have performed similar transactions earlier. That is, in addition to being financially close, we assume that the likelihood for interacting increases if two agents have interacted earlier.
|
|
We add this feature by modifying the previous likelihood to
|
|
$$
|
|
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha}\left(c_{ij}+1\right)^{\gamma},
|
|
$$
|
|
|
|
where \( c_{ij} \) represents the number of previous interactions that have taken place between \( i \) and \( j \). The factor \( 1 \) is added in order to ensure that if they have not interacted earlier they can still interact. Perform similar studies as above with \( N=1000 \), \( \alpha=1.0 \) and \( \alpha=2.0 \) using \( \gamma = 0.0, 1.0, 2.0, 3.0 \) and \( 4.0 \). Plot the wealth distributions for these cases and try to extract eventual power law tails with and without a saving \( \lambda \) in each transaction. Comment your results and compare them with figures 5 and 6 of <a href="http://www.sciencedirect.com/science/article/pii/S0378437114006967" target="_self">Goswami and Sen</a>.
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
</div> <!-- end container -->
|
|
<!-- include javascript, jQuery *first* -->
|
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
|
|
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
|
|
|
|
<!-- Bootstrap footer
|
|
<footer>
|
|
<a href="http://..."><img width="250" align=right src="http://..."></a>
|
|
</footer>
|
|
-->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|