Files
FYS-STK4155/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb
T
2018-05-29 08:18:42 -04:00

1722 lines
63 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters -->\n",
"# Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters\n",
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **May 29, 2018**\n",
"\n",
"Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"## Introduction\n",
"\n",
"Our emphasis throughout this series of lectures \n",
"is on understanding the mathematical aspects of\n",
"different algorithms used in the fields of data analysis and machine learning. \n",
"\n",
"However, where possible we will emphasize the\n",
"importance of using available software. We start thus with a hands-on\n",
"and top-down approach to machine learning. The aim is thus to start with\n",
"relevant data or data we have produced \n",
"and use these to introduce statistical data analysis\n",
"concepts and machine learning algorithms before we delve into the\n",
"algorithms themselves. The examples we will use in the beginning, start with simple\n",
"polynomials with random noise added. We will use the Python\n",
"software package [Scikit-learn](http://scikit-learn.org/stable/) and\n",
"introduce various machine learning algorithms to make fits of\n",
"the data and predictions. We move thereafter to more interesting\n",
"cases such as the simulation of financial transactions or disease\n",
"models. These are examples where we can easily set up the data and\n",
"then use machine learning algorithms included in for example\n",
"**scikit-learn**. \n",
"\n",
"These examples will serve us the purpose of getting\n",
"started. Furthermore, they allow us to catch more than two birds with\n",
"a stone. They will allow us to bring in some programming specific\n",
"topics and tools as well as showing the power of various Python (and\n",
"R) packages for machine learning and statistical data analysis. In the\n",
"lectures on linear algebra we cover in more detail various programming\n",
"features of languages like Python and C++ (and other), we will also\n",
"look into more specific linear functions which are relevant for the\n",
"various algorithms we will discuss. Here, we will mainly focus on two\n",
"specific Python packages for Machine Learning, scikit-learn and\n",
"tensorflow (see below for links etc). Moreover, the examples we\n",
"introduce will serve as inputs to many of our discussions later, as\n",
"well as allowing you to set up models and produce your own data and\n",
"get started with programming.\n",
"\n",
"\n",
"\n",
"\n",
"## Software and needed installations\n",
"\n",
"We will make extensive use of Python as programming language and its\n",
"myriad of available libraries. You will find\n",
"IPython/Jupyter notebooks invaluable in your work. You can run **R**\n",
"codes in the Jupyter/IPython notebooks, with the immediate benefit of\n",
"visualizing your data. You can also use compiled languages like C++,\n",
"Rust, Fortran etc if you prefer. The focus in these lectures will be\n",
"on Python, but we will provide many code examples for those of you who\n",
"prefer R or compiled languages. You can integrate C++ codes and R in for example\n",
"a Jupyter notebook. \n",
"\n",
"\n",
"If you have Python installed (we recommend Python3) and you feel\n",
"pretty familiar with installing different packages, we recommend that\n",
"you install the following Python packages via **pip** as \n",
"\n",
"1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n",
"\n",
"For Python3, replace **pip** with **pip3**.\n",
"\n",
"For OSX users we recommend, after having installed Xcode, to\n",
"install **brew**. Brew allows for a seamless installation of additional\n",
"software via for example \n",
"\n",
"1. brew install python3\n",
"\n",
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n",
"you can use **pip** as well and simply install Python as \n",
"\n",
"1. sudo apt-get install python3 (or python for pyhton2.7)\n",
"\n",
"etc etc. \n",
"\n",
"## Python installers\n",
"\n",
"If you don't want to perform these operations separately and venture\n",
"into the hassle of exploring how to set up dependencies and paths, we\n",
"recommend two widely used distrubutions which set up all relevant\n",
"dependencies for Python, namely \n",
"\n",
"* [Anaconda](https://docs.anaconda.com/), \n",
"\n",
"which is an open source\n",
"distribution of the Python and R programming languages for large-scale\n",
"data processing, predictive analytics, and scientific computing, that\n",
"aims to simplify package management and deployment. Package versions\n",
"are managed by the package management system **conda**. \n",
"\n",
"* [Enthought canopy](https://www.enthought.com/product/canopy/) \n",
"\n",
"is a Python\n",
"distribution for scientific and analytic computing distribution and\n",
"analysis environment, available for free and under a commercial\n",
"license.\n",
"\n",
"\n",
"## Installing R, C++, cython or Julia\n",
"\n",
"You will also find it convenient to utilize R. Although we will mainly\n",
"use Python during lectures and in various projects and exercises, we\n",
"provide a full R set of codes for the same examples. Those of you\n",
"already familiar with R should feel free to continue using R, keeping\n",
"however an eye on the parallel Python set ups. Similarly, if you are a\n",
"Python afecionado, feel free to explore R as well. Jupyter/Ipython\n",
"notebook allows you to run **R** codes interactively in your\n",
"browser. The software library **R** is tuned to statistically analysis\n",
"and allows for an easy usage of the tools we will discuss in these\n",
"texts.\n",
"\n",
"To install **R** with Jupyter notebook \n",
"[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n",
"\n",
"\n",
"\n",
"## Installing R, C++, cython, Numba etc\n",
"\n",
"\n",
"For the C++ aficionados, Jupyter/IPython notebook allows you also to\n",
"install C++ and run codes written in this language interactively in\n",
"the browser. Since we will emphasize writing many of the algorithms\n",
"yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming\n",
"languages.\n",
"\n",
"To add more entropy, **cython** can also be used when running your\n",
"notebooks. It means that Python with the Jupyter/IPython notebook\n",
"setup allows you to integrate widely popular softwares and tools for\n",
"scientific computing. Similarly, the \n",
"[Numba Python package](https://numba.pydata.org/) delivers increased performance\n",
"capabilities with minimal rewrites of your codes. With its\n",
"versatility, including symbolic operations, Python offers a unique\n",
"computational environment. Your Jupyter/IPython notebook can easily be\n",
"converted into a nicely rendered **PDF** file or a Latex file for\n",
"further processing. For example, convert to latex as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" pycod jupyter nbconvert filename.ipynb --to latex \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n",
"\n",
"Finally, if you wish to use the light mark-up language \n",
"[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n",
"formats, ipython notebooks, latex files, pdf files etc with minimal edits.\n",
"\n",
"## Simple linear regression model using **scikit-learn**\n",
"\n",
"We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n",
"What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n",
"\n",
"\n",
"The Numpy functions are imported used the **import numpy as np**\n",
"statement and the random number generator for the uniform distribution\n",
"is called using the function **np.random.rand()**, where we specificy\n",
"that we want $100$ random variables. Using Numpy we define\n",
"automatically an array with the specified number of elements, $100$ in\n",
"our case. With the Numpy function **randn()** we can compute random\n",
"numbers with the normal distribution (mean value $\\mu$ equal to zero and\n",
"variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n",
"dependence as function of $x$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y = 2x+N(0,1),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $N(0,1)$ represents random numbers generated by the normal\n",
"distribution. From **scikit-learn** we import then the\n",
"**LinearRegression** functionality and make a prediction $\\tilde{y} =\n",
"\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n",
"data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n",
"**scikit-learn** has also a functionality which extracts the above\n",
"fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n",
"distinguish between training data and test data.\n",
"\n",
"For plotting we use the Python package\n",
"[matplotlib](https://matplotlib.org/) which produces publication\n",
"quality figures. Feel free to explore the extensive\n",
"[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n",
"this example we plot our original values of $x$ and $y$ as well as the\n",
"prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n",
"data with a straight line.\n",
"\n",
"The Python code follows here."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"# Importing various packages\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 2*x+np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"xnew = np.array([[0],[1]])\n",
"ypredict = linreg.predict(xnew)\n",
"\n",
"plt.plot(xnew, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0,1.0,0, 5.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Simple Linear Regression')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This example serves several aims. It allows us to demonstrate several\n",
"aspects of data analysis and later machine learning algorithms. The\n",
"immediate visualization shows that our linear fit is not\n",
"impressive. It goes through the data points, but there are many\n",
"outliers which are not reproduced by our linear regression. We could\n",
"now play around with this small program and change for example the\n",
"factor in front of $x$ and the normal distribution. Try to change the\n",
"function $y$ to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y = 10x+0.01 \\times N(0,1),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $x$ is defined as before. Does the fit look better? Indeed, by\n",
"reducing the role of the normal distribution we see immediately that\n",
"our linear prediction seemingly reproduces better the training\n",
"set. However, this testing 'by the eye' is obviouly not satisfactory in the\n",
"long run. Here we have only defined the training data and our model, and \n",
"have not discussed a more rigorous approach to the **cost** function.\n",
"\n",
"We need more rigorous criteria in defining whether we have succeeded or\n",
"not in modeling our training data. You will be surprised to see that\n",
"many scientists seldomly venture beyond this 'by the eye' approach. A\n",
"standard approach for the *cost* function is the so-called $\\chi^2$\n",
"function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\chi^2 = \\frac{1}{n}\n",
"\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n",
"$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n",
"however the aim of scaling the equations and make the cost function\n",
"dimensionless. \n",
"\n",
"Minimizing the cost function is a central aspect of\n",
"our discussions to come. Finding its minima as function of the model\n",
"parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n",
"theme in these series of lectures. Essentially all machine learning\n",
"algorithms we will discuss center around the minimization of the\n",
"chosen cost function. This depends in turn on our specific\n",
"model for describing the data, a typical situation in supervised\n",
"learning. Automatizing the search for the minima of the cost function is a\n",
"central ingredient in all algorithms. Typical methods which are\n",
"employed are various variants of **gradient** methods. These will be\n",
"discussed in more detail later. Again, you'll be surprised to hear that\n",
"many practitioners minimize the above function ''by the eye', popularly dubbed as \n",
"'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n",
"the $\\chi^2$ function becomes smaller. \n",
"\n",
"There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n",
"the relative error as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can modify easily the above Python code and plot the relative instead"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 5*x+0.01*np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"ypredict = linreg.predict(x)\n",
"\n",
"plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n",
"plt.axis([0,1.0,0.0, 0.5])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n",
"plt.title(r'Relative error')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Depending on the parameter in front of the normal distribution, we may\n",
"have a small or larger relative error. Try to play around with\n",
"different training data sets and study (graphically) the value of the\n",
"relative error.\n",
"\n",
"As mentioned above, **scikit-learn** has an impressive functionality.\n",
"We can for example extract the values of $\\alpha$ and $\\beta$ and\n",
"their error estimates, or the variance and standard deviation and many\n",
"other properties from the statistical data analysis. \n",
"\n",
"Here we show an\n",
"example of the functionality of scikit-learn."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np \n",
"import matplotlib.pyplot as plt \n",
"from sklearn.linear_model import LinearRegression \n",
"from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 2.0+ 5*x+0.5np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"ypredict = linreg.predict(x)\n",
"print('The intercept alpha: \\n', linreg.intercept_)\n",
"print('Coefficient beta : \\n', linreg.coef_)\n",
"# The mean squared error \n",
"print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n",
"# Explained variance score: 1 is perfect prediction \n",
"print('Variance score: %.2f' % r2_score(y, ypredict))\n",
"# Mean squared log error \n",
"print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n",
"# Mean absolute error \n",
"print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n",
"plt.plot(x, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0.0,1.0,1.5, 7.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Linear Regression fit ')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n",
"$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n",
"\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The smaller the value, the better the fit. Ideally we would like to\n",
"have an MSE equal zero. The attentive reader has probably recognized\n",
"this function as being similar to the $\\chi^2$ function defined above.\n",
"\n",
"The **r2score** function computes $R^2$, the coefficient of\n",
"determination. It provides a measure of how well future samples are\n",
"likely to be predicted by the model. Best possible score is 1.0 and it\n",
"can be negative (because the model can be arbitrarily worse). A\n",
"constant model that always predicts the expected value of $\\hat{y}$,\n",
"disregarding the input features, would get a $R^2$ score of $0.0$.\n",
"\n",
"If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have defined the mean value of $\\hat{y}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another quantity will meet again in our discussions of regression analysis is \n",
" mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n",
"The MAE is defined as follows"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally we present the \n",
"squared logarithmic (quadratic) error"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n",
"estimate is best to use when targets having exponential growth, such\n",
"as population counts, average sales of a commodity over a span of\n",
"years etc. \n",
"\n",
"We will discuss in more\n",
"detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n",
"a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import Ridge\n",
"from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn.pipeline import make_pipeline\n",
"\n",
"def f(x):\n",
" \"\"\" function to approximate by polynomial interpolation\"\"\"\n",
" return x*x*x\n",
"\n",
"# generate points used to plot \n",
"x_plot = np.linspace(0, 10, 100)\n",
"\n",
"# generate points and keep a subset of them \n",
"x = np.linspace(0, 10, 100)\n",
"rng = np.random.RandomState(0)\n",
"rng.shuffle(x)\n",
"x = np.sort(x[:20])\n",
"y = f(x)\n",
"# create matrix versions of these arrays \n",
"X = x[:, np.newaxis]\n",
"X_plot = x_plot[:, np.newaxis]\n",
"\n",
"colors = ['teal', 'yellowgreen', 'gold']\n",
"lw = 2\n",
"plt.plot(x_plot, f(x_plot), color='cornflowerblue', linewidth=lw,\n",
" label=\"ground truth\")\n",
"plt.scatter(x, y, color='navy', s=30, marker='o', label=\"training points\")\n",
"\n",
"for count, degree in enumerate([3, 4, 5]):\n",
" model = make_pipeline(PolynomialFeatures(degree), Ridge())\n",
" model.fit(X, y)\n",
" y_plot = model.predict(X_plot)\n",
" plt.plot(x_plot, y_plot, color=colors[count], linewidth=lw,\n",
" label=\"degree %d\" % degree)\n",
"\n",
"plt.legend(loc='lower left')\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Non-Linear Least squares in R"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" set.seed(1485)\n",
" len = 24\n",
" x = runif(len)\n",
" y = x^3+rnorm(len, 0,0.06)\n",
" ds = data.frame(x = x, y = y)\n",
" str(ds)\n",
" plot( y ~ x, main =\"Known cubic with noise\")\n",
" s = seq(0,1,length =100)\n",
" lines(s, s^3, lty =2, col =\"green\")\n",
" m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)\n",
" class(m)\n",
" summary(m)\n",
" power = round(summary(m)$coefficients[1], 3)\n",
" power.se = round(summary(m)$coefficients[2], 3)\n",
" plot(y ~ x, main = \"Fitted power model\", sub = \"Blue: fit; green: known\")\n",
" s = seq(0, 1, length = 100)\n",
" lines(s, s^3, lty = 2, col = \"green\")\n",
" lines(s, predict(m, list(x = s)), lty = 1, col = \"blue\")\n",
" text(0, 0.5, paste(\"y =x^ (\", power, \" +/- \", power.se, \")\", sep = \"\"), pos = 4)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another useful Python package is\n",
"[pandas](https://pandas.pydata.org/), which is an open source library\n",
"providing high-performance, easy-to-use data structures and data\n",
"analysis tools for Python. The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, city of residence and age, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import pandas as pd\n",
"from IPython.display import display\n",
"data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Nairobi\", \"Napoli\", \"London\", \"Buenos Aires\"], 'Age':[51, 21, 34, 45]}\n",
"data_pandas = pd.DataFrame(data)\n",
"display(data_pandas)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Predator-Prey model from ecology\n",
"\n",
"The population dynamics of a simple predator-prey system is a\n",
"classical example shown in many biology textbooks when ecological\n",
"systems are discussed. The system contains all elements of the\n",
"scientific method:\n",
"\n",
" * The set up of a specific hypothesis combined with\n",
"\n",
" * the experimental methods needed (one can study existing data or perform experiments)\n",
"\n",
" * analyzing and interpreting the data and performing further experiments if needed\n",
"\n",
" * trying to extract general behaviors and extract eventual laws or patterns\n",
"\n",
" * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments\n",
"\n",
"\n",
"\n",
"\n",
"## Case study from Hudson bay\n",
"\n",
"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?\n",
"Here we start by\n",
"\n",
"1. plotting the data\n",
"\n",
"2. derive a simple model for the population dynamics\n",
"\n",
"3. (fitting parameters in the model to the data)\n",
"\n",
"4. using the model predict the evolution other predator-pray systems\n",
"\n",
"\n",
"\n",
"## Hudson bay data\n",
"\n",
"\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"\n",
"<table border=\"1\">\n",
"<thead>\n",
"<tr><th align=\"center\">Year</th> <th align=\"center\">Hares (x1000)</th> <th align=\"center\">Lynx (x1000)</th> </tr>\n",
"</thead>\n",
"<tbody>\n",
"<tr><td align=\"left\"> 1900 </td> <td align=\"right\"> 30.0 </td> <td align=\"right\"> 4.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1901 </td> <td align=\"right\"> 47.2 </td> <td align=\"right\"> 6.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1902 </td> <td align=\"right\"> 70.2 </td> <td align=\"right\"> 9.8 </td> </tr>\n",
"<tr><td align=\"left\"> 1903 </td> <td align=\"right\"> 77.4 </td> <td align=\"right\"> 35.2 </td> </tr>\n",
"<tr><td align=\"left\"> 1904 </td> <td align=\"right\"> 36.3 </td> <td align=\"right\"> 59.4 </td> </tr>\n",
"<tr><td align=\"left\"> 1905 </td> <td align=\"right\"> 20.6 </td> <td align=\"right\"> 41.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1906 </td> <td align=\"right\"> 18.1 </td> <td align=\"right\"> 19.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1907 </td> <td align=\"right\"> 21.4 </td> <td align=\"right\"> 13.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1908 </td> <td align=\"right\"> 22.0 </td> <td align=\"right\"> 8.3 </td> </tr>\n",
"<tr><td align=\"left\"> 1909 </td> <td align=\"right\"> 25.4 </td> <td align=\"right\"> 9.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1910 </td> <td align=\"right\"> 27.1 </td> <td align=\"right\"> 7.4 </td> </tr>\n",
"<tr><td align=\"left\"> 1911 </td> <td align=\"right\"> 40.3 </td> <td align=\"right\"> 8.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1912 </td> <td align=\"right\"> 57 </td> <td align=\"right\"> 12.3 </td> </tr>\n",
"<tr><td align=\"left\"> 1913 </td> <td align=\"right\"> 76.6 </td> <td align=\"right\"> 19.5 </td> </tr>\n",
"<tr><td align=\"left\"> 1914 </td> <td align=\"right\"> 52.3 </td> <td align=\"right\"> 45.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1915 </td> <td align=\"right\"> 19.5 </td> <td align=\"right\"> 51.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1916 </td> <td align=\"right\"> 11.2 </td> <td align=\"right\"> 29.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1917 </td> <td align=\"right\"> 7.6 </td> <td align=\"right\"> 15.8 </td> </tr>\n",
"<tr><td align=\"left\"> 1918 </td> <td align=\"right\"> 14.6 </td> <td align=\"right\"> 9.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1919 </td> <td align=\"right\"> 16.2 </td> <td align=\"right\"> 10.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1920 </td> <td align=\"right\"> 24.7 </td> <td align=\"right\"> 8.6 </td> </tr>\n",
"</tbody>\n",
"</table>\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Plotting the data"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"from matplotlib import pyplot as plt\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"# Make arrays containing x-axis and hares and lynx populations\n",
"year = data[:,0]\n",
"hares = data[:,1]\n",
"lynx = data[:,2]\n",
"\n",
"plt.plot(year, hares ,'b-+', year, lynx, 'r-o')\n",
"plt.axis([1900,1920,0, 100.0])\n",
"plt.xlabel(r'Year')\n",
"plt.ylabel(r'Numbers of hares and lynx ')\n",
"plt.legend(('Hares','Lynx'), loc='upper right')\n",
"plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')\n",
"plt.savefig('Hudson_Bay_data.pdf')\n",
"plt.savefig('Hudson_Bay_data.png')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Hares and lynx in Hudson bay from 1900 to 1920\n",
"\n",
"<!-- dom:FIGURE: [fig/Hudson_Bay_data.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<p></p>\n",
"<img src=\"fig/Hudson_Bay_data.png\" width=700>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"\n",
"\n",
"## Why now create a computer model for the hare and lynx populations?\n",
"We see from the plot that there are indeed fluctuations.\n",
"We would like to create a mathematical model that explains these\n",
"population fluctuations. Ecologists have predicted that in a simple\n",
"predator-prey system that a rise in prey population is followed (with\n",
"a lag) by a rise in the predator population. When the predator\n",
"population is sufficiently high, then the prey population begins\n",
"dropping. After the prey population falls, then the predator\n",
"population falls, which allows the prey population to recover and\n",
"complete one cycle of this interaction. Thus, we see that\n",
"qualitatively oscillations occur. Can a mathematical model predict\n",
"this? What causes cycles to slow or speed up? What affects the\n",
"amplitude of the oscillation or do you expect to see the oscillations\n",
"damp to a stable equilibrium? The models tend to ignore factors like\n",
"climate and other complicating factors. How significant are these?\n",
"\n",
" * We see oscillations in the data\n",
"\n",
" * What causes cycles to slow or speed up?\n",
"\n",
" * What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?\n",
"\n",
" * With a model we can better *understand the data*\n",
"\n",
" * More important: we can understand the ecology dynamics of\n",
" predator-pray populations\n",
"\n",
"\n",
"\n",
"\n",
"## The traditional (top-down) approach\n",
"\n",
"The classical way (in all books) is to present the Lotka-Volterra equations:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"\\frac{dH}{dt} &= H(a - b L)\\\\\n",
"\\frac{dL}{dt} &= - L(d - c H)\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here,\n",
"\n",
" * $H$ is the number of preys\n",
"\n",
" * $L$ the number of predators\n",
"\n",
" * $a$, $b$, $d$, $c$ are parameters\n",
"\n",
"Most books quickly establish the model and then use considerable space on\n",
"discussing the qualitative properties of this *nonlinear system of\n",
"ODEs* (which cannot be solved)\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Basic mathematics notation\n",
" * Time points: $t_0,t_1,\\ldots,t_m$\n",
"\n",
" * Uniform distribution of time points: $t_n=n\\Delta t$\n",
"\n",
" * $H^n$: population of hares at time $t_n$\n",
"\n",
" * $L^n$: population of lynx at time $t_n$\n",
"\n",
" * We want to model the changes in populations, $\\Delta H=H^{n+1}-H^n$\n",
" and $\\Delta L=L^{n+1}-L^n$ during a general time interval $[t_{n+1},t_n]$\n",
" of length $\\Delta t=t_{n+1}-t_n$\n",
"\n",
"\n",
"\n",
"## Basic dynamics of the population of hares\n",
"\n",
"The population of hares evolves due to births and deaths exactly as a bacteria population:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta H = a \\Delta t H^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, hares have an additional loss in the population because\n",
"they are eaten by lynx.\n",
"All the hares and lynx can form\n",
"$H\\cdot L$ pairs in total. When such pairs meet during a time\n",
"interval $\\Delta t$, there is some\n",
"small probablity that the lynx will eat the hare.\n",
"So in fraction $b\\Delta t HL$, the lynx eat hares. This\n",
"loss of hares must be accounted for. Subtracted in the equation for hares:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta H = a\\Delta t H^n - b \\Delta t H^nL^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Basic dynamics of the population of lynx\n",
"\n",
"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.\n",
"In a time interval $\\Delta t HL$ hares and lynx can meet, and in a\n",
"fraction $b\\Delta t HL$ the lynx eats the hare. All of this does not\n",
"contribute to the growth of lynx, again just a fraction of\n",
"$b\\Delta t HL$ that we write as\n",
"$d\\Delta t HL$. In addition, lynx die just as in the population\n",
"dynamics with one isolated animal population, leading to a loss\n",
"$-c\\Delta t L$.\n",
"\n",
"\n",
"\n",
"The accounting of lynx then looks like"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta L = d\\Delta t H^nL^n - c\\Delta t L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evolution equations\n",
"\n",
"By writing up the definition of $\\Delta H$ and $\\Delta L$, and putting\n",
"all assumed known terms $H^n$ and $L^n$ on the right-hand side, we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"H^{n+1} = H^n + a\\Delta t H^n - b\\Delta t H^n L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"L^{n+1} = L^n + d\\Delta t H^nL^n - c\\Delta t L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note:\n",
"\n",
" * These equations are ready to be implemented!\n",
"\n",
" * But to start, we need $H^0$ and $L^0$ \n",
" (which we can get from the data)\n",
"\n",
" * We also need values for $a$, $b$, $d$, $c$\n",
"\n",
"\n",
"\n",
"## Adapt the model to the Hudson Bay case\n",
"\n",
" * As always, models tend to be general - as here, applicable\n",
" to \"all\" predator-pray systems\n",
"\n",
" * The critical issue is whether the *interaction* between hares and lynx\n",
" is sufficiently well modeled by $\\hbox{const}HL$\n",
"\n",
" * The parameters $a$, $b$, $d$, and $c$ must be\n",
" estimated from data\n",
"\n",
" * Measure time in years\n",
"\n",
" * $t_0=1900$, $t_m=1920$\n",
"\n",
"\n",
"\n",
"## The program"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def solver(m, H0, L0, dt, a, b, c, d, t0):\n",
" \"\"\"Solve the difference equations for H and L over m years\n",
" with time step dt (measured in years.\"\"\"\n",
"\n",
" num_intervals = int(m/float(dt))\n",
" t = np.linspace(t0, t0 + m, num_intervals+1)\n",
" H = np.zeros(t.size)\n",
" L = np.zeros(t.size)\n",
"\n",
" print('Init:', H0, L0, dt)\n",
" H[0] = H0\n",
" L[0] = L0\n",
"\n",
" for n in range(0, len(t)-1):\n",
" H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]\n",
" L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]\n",
" return H, L, t\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"# Make arrays containing x-axis and hares and lynx populations\n",
"t_e = data[:,0]\n",
"H_e = data[:,1]\n",
"L_e = data[:,2]\n",
"\n",
"# Simulate using the model\n",
"H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,\n",
" a=0.4807, b=0.02482, c=0.9272, d=0.02756,\n",
" t0=1900)\n",
"\n",
"# Visualize simulations and data\n",
"plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')\n",
"plt.xlabel('Year')\n",
"plt.ylabel('Numbers of hares and lynx')\n",
"plt.axis([1900, 1920, 0, 140])\n",
"plt.title(r'Population of hares and lynx 1900-1920 (x1000)')\n",
"plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')\n",
"plt.savefig('Hudson_Bay_sim.pdf')\n",
"plt.savefig('Hudson_Bay_sim.png')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The plot\n",
"\n",
"<!-- dom:FIGURE: [fig/Hudson_Bay_sim.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<p></p>\n",
"<img src=\"fig/Hudson_Bay_sim.png\" width=700>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"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.\n",
"\n",
"\n",
"## Linear regression in Python"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from IPython.display import display\n",
"import sklearn\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
"\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"x = data[:,0]\n",
"y = data[:,1]\n",
"line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)\n",
"reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))\n",
"plt.plot(line, reg.predict(line), label=\"decision tree\")\n",
"regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))\n",
"plt.plot(line, regline.predict(line), label= \"Linear Regression\")\n",
"plt.plot(x, y, label= \"Linear Regression\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear Least squares in R"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" HudsonBay = read.csv(\"src/Hudson_Bay.csv\",header=T)\n",
" fix(HudsonBay)\n",
" dim(HudsonBay)\n",
" names(HudsonBay)\n",
" plot(HudsonBay$Year, HudsonBay$Hares..x1000.)\n",
" attach(HudsonBay)\n",
" plot(Year, Hares..x1000.)\n",
" plot(Year, Hares..x1000., col=\"red\", varwidth=T, xlab=\"Years\", ylab=\"Haresx 1000\")\n",
" summary(HudsonBay)\n",
" summary(Hares..x1000.)\n",
" library(MASS)\n",
" library(ISLR)\n",
" scatter.smooth(x=Year, y = Hares..x1000.)\n",
" linearMod = lm(Hares..x1000. ~ Year)\n",
" print(linearMod)\n",
" summary(linearMod)\n",
" plot(linearMod)\n",
" confint(linearMod)\n",
" predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval=\"confidence\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: ecoli lab experiment\n",
"\n",
"\n",
"**Typical pattern:**\n",
"\n",
"The population grows faster and faster. [Why? Is there an underlying (general) mechanism](http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html)?\n",
"\n",
"\n",
"1. Cells divide after $T$ seconds on average (one generation)\n",
"\n",
"2. $2N$ celles divide into twice as many new cells $\\Delta N$ in a time\n",
" interval $\\Delta t$ as $N$ cells would: $\\Delta N \\propto N$\n",
"\n",
"3. $N$ cells result in twice as many new individuals $\\Delta N$ in\n",
" time $2\\Delta t$ as in time $\\Delta t$: $\\Delta N \\propto\\Delta t$\n",
"\n",
"4. Same proportionality wrt death (repeat reasoning)\n",
"\n",
"5. Proposed model: $\\Delta N = b\\Delta t N - d\\Delta tN$ for some unknown\n",
" constants $b$ (births) and $d$ (deaths)\n",
"\n",
"6. Describe evolution in discrete time: $t_n=n\\Delta t$\n",
"\n",
"7. Program-friendly notation: $N$ at $t_n$ is $N^n$\n",
"\n",
"8. Math model: $N^{n+1} = N^n + r\\Delta t\\, N$ (with $\\ r=b-d$)\n",
"\n",
"9. Program model: `N[n+1] = N[n] + r*dt*N[n]`\n",
"\n",
"\n",
"\n",
"## The program\n",
"\n",
"Let us solve the difference equation in as simple way as possible,\n",
"just to train some programming: $r=1.5$, $N^0=1$, $\\Delta t=0.5$"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"t = np.linspace(0, 10, 21) # 20 intervals in [0, 10]\n",
"dt = t[1] - t[0]\n",
"N = np.zeros(t.size)\n",
"\n",
"N[0] = 1\n",
"r = 0.5\n",
"\n",
"for n in range(0, N.size-1, 1):\n",
" N[n+1] = N[n] + r*dt*N[n]\n",
" print 'N[%d]=%.1f' % (n+1, N[n+1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"% if FORMAT != 'ipynb':\n",
"## The output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" N[1]=1.2\n",
" N[2]=1.6\n",
" N[3]=2.0\n",
" N[4]=2.4\n",
" N[5]=3.1\n",
" N[6]=3.8\n",
" N[7]=4.8\n",
" N[8]=6.0\n",
" N[9]=7.5\n",
" N[10]=9.3\n",
" N[11]=11.6\n",
" N[12]=14.6\n",
" N[13]=18.2\n",
" N[14]=22.7\n",
" N[15]=28.4\n",
" N[16]=35.5\n",
" N[17]=44.4\n",
" N[18]=55.5\n",
" N[19]=69.4\n",
" N[20]=86.7\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"% endif\n",
"\n",
"## Parameter estimation\n",
"\n",
" * We do not know $r$\n",
"\n",
" * How can we estimate $r$ from data?\n",
"\n",
"We can use the difference equation with the experimental data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"N^{n+1} = N^n + r\\Delta t N^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Say $N^{n+1}$ and $N^n$ are known from data, solve wrt $r$:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"r = \\frac{N^{n+1}-N^n}{N^n\\Delta t}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use experimental data in the fraction, say $t_1=600$, $t_2=1200$,\n",
"$N^1=140$, $N^2=250$: $r=0.0013$.\n",
"\n",
"\n",
"\n",
"\n",
"## A program relevant for the biological problem\n",
"\n",
"<!-- exact r = 0.000694 -->"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Estimate r\n",
"data = np.loadtxt('ecoli.csv', delimiter=',')\n",
"t_e = data[:,0]\n",
"N_e = data[:,1]\n",
"i = 2 # Data point (i,i+1) used to estimate r\n",
"r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i]))\n",
"print 'Estimated r=%.5f' % r\n",
"# Can experiment with r values and see if the model can\n",
"# match the data better\n",
"\n",
"T = 1200 # cell can divide after T sec\n",
"t_max = 5*T # 5 generations in experiment\n",
"t = np.linspace(0, t_max, 1000)\n",
"dt = t[1] - t[0]\n",
"N = np.zeros(t.size)\n",
"\n",
"N[0] = 100\n",
"for n in range(0, len(t)-1, 1):\n",
" N[n+1] = N[n] + r*dt*N[n]\n",
"\n",
"import matplotlib.pyplot as plt\n",
"plt.plot(t, N, 'r-', t_e, N_e, 'bo')\n",
"plt.xlabel('time [s]'); plt.ylabel('N')\n",
"plt.legend(['model', 'experiment'], loc='upper left')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Change `r` in the program and play around to make a better fit!\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Simulating financial transactions\n",
"\n",
"The aim here is to simulate financial transactions among financial agents\n",
"using Monte Carlo methods. The final goal is to extract a distribution of income as function\n",
"of the income $m$. From Pareto's work ([V. Pareto, 1897](http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto)) it is known from empirical studies\n",
"that the higher end of the distribution of money follows a distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m\\propto m^{-1-\\alpha},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $\\alpha\\in [1,2]$. We will here follow the analysis made by [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327). \n",
"\n",
"Here we will study numerically the relation between the micro-dynamic relations among financial \n",
"agents and the resulting macroscopic money distribution.\n",
"\n",
"We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents\n",
"start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair\n",
"of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes\n",
"to $m_i'$ and similarly we have $m_j\\rightarrow m_j'$. \n",
"Money is conserved during a transaction, meaning that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:conserve\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" m_i+m_j=m_i'+m_j'.\n",
"\\label{eq:conserve} \\tag{1}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The change is done via a random reassignement (a random number) $\\epsilon$, meaning that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i' = \\epsilon(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"leading to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j'= (1-\\epsilon)(m_i+m_j).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The number $\\epsilon$ is extracted from a uniform distribution.\n",
"In this simple model, no agents are left with a debt, that is $m\\ge 0$.\n",
"Due to the conservation law above, one can show that the system relaxes toward an equilibrium\n",
"state given by a Gibbs distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m=\\beta \\exp{(-\\beta m)},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta = \\frac{1}{\\langle m\\rangle},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and $\\langle m\\rangle=\\sum_i m_i/N=m_0$, the average money.\n",
"It means that after equilibrium has been reached that the majority of agents is left with a small\n",
"number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,\n",
"exponentially decreases with $m'$.\n",
"\n",
"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\n",
"several runs of the above simulations, at least $10^3-10^4$ runs (experiments).\n",
"\n",
"\n",
"\n",
"\n",
"### Simulation of Transactions\n",
"\n",
"Our task is to first set up an algorithm which simulates the above transactions with an initial\n",
" amount $m_0$.\n",
" The challenge here is to figure out a Monte Carlo simulation based on the\n",
" above equations.\n",
" You will in particular need to make an algorithm which sets up a histogram as function of $m$.\n",
" This histogram contains the number of times a value $m$ is registered and represents\n",
" $w_m\\Delta m$. You will need to set up a value for the interval $\\Delta m$ (typically $0.01-0.05$).\n",
" That means you need to account for the number of times you register an income in the interval\n",
" $m,m+\\Delta m$. The number of times you register this income, represents the value that enters the histogram.\n",
" You will also need to find a criterion for when the equilibrium situation has been reached."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#!/usr/bin/env python\n",
"import numpy as np\n",
"import matplotlib.mlab as mlab\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"\n",
"# initialize the rng with a seed\n",
"random.seed()\n",
"# Hard coding of input parameters\n",
"Agents = 500\n",
"MCcounts = 1000\n",
"Transactions = 100000\n",
"startMoney = 1.0\n",
"Lambda = 0.0\n",
"FinancialAgents = startMoney*np.ones(Agents)\n",
"for i in range (1, MCcounts, 1):\n",
" for j in range (1, Transactions, 1):\n",
" agent_i = int(Agents*random.random())\n",
" agent_j = int(Agents*random.random())\n",
" epsilon = random.random()\n",
" if agent_i != agent_j:\n",
" m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n",
" m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n",
" FinancialAgents[agent_i] = m1\n",
" FinancialAgents[agent_j] = m2\n",
"\n",
"# the histogram of the data\n",
"n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green')\n",
"\n",
"plt.xlabel('$x$')\n",
"plt.ylabel('Distribution of wealth')\n",
"plt.title(r'Money')\n",
"plt.axis([0, 10, 0, 500])\n",
"plt.grid(True)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then change our model to allow for a saving criterion, meaning that the agents save\n",
" 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.\n",
"\n",
" The conservation law of Eq. ([eq:conserve](#eq:conserve)) holds, but the money to be shared in a transaction between\n",
" agent $i$ and agent $j$ is now $(1-\\lambda)(m_i+m_j)$. This means that we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i' = \\lambda m_i+\\epsilon(1-\\lambda)(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j' = \\lambda m_j+(1-\\epsilon)(1-\\lambda)(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which can be written as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i'=m_i+\\delta m\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j'=m_j-\\delta m,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\delta m=(1-\\lambda)(\\epsilon m_j-(1-\\epsilon)m_i),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"showing how money is conserved during a transaction.\n",
" Select values of $\\lambda =0.25,0.5$ and $\\lambda=0.9$ and try to extract the corresponding\n",
" equilibrium distributions and compare these with the Gibbs distribution. Comment your results.\n",
"Extract a parametrization of the above curves, see for example [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327) and see if you can parametrize the high-end tails of the distributions in terms of power laws. Comment your results.\n",
"\n",
"In the studies above the agents were selected randomly, irrespective of whether we allowed for\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{ij} \\propto \\vert m_i-m_j\\vert^{-\\alpha},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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). \n",
"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$. \n",
"You should try to reproduce Figure 1 of [Goswami and Sen](http://www.sciencedirect.com/science/article/pii/S0378437114006967). \n",
"Extract the tail of the distribution and see if it follows a Pareto distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m\\propto m^{-1-\\alpha}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What happens if $\\alpha \\gg 1$?\n",
"\n",
"Perform the analysis with and without a saving $\\lambda$ on each transaction and comment your results. \n",
"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. \n",
"We add this feature by modifying the previous likelihood to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{ij} \\propto \\vert m_i-m_j\\vert^{-\\alpha}\\left(c_{ij}+1\\right)^{\\gamma},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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 [Goswami and Sen](http://www.sciencedirect.com/science/article/pii/S0378437114006967). \n",
"\n",
"## Particle in one dimension an velocity distribution"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Program to test the Metropolis algorithm with one particle at given temp in one dimension\n",
"import numpy as np\n",
"import matplotlib.mlab as mlab\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"from math import sqrt, exp, log\n",
"# initialize the rng with a seed\n",
"random.seed()\n",
"# Hard coding of input parameters\n",
"MCcycles = 100000\n",
"Temperature = 2.0\n",
"beta = 1./Temperature\n",
"InitialVelocity = -2.0\n",
"CurrentVelocity = InitialVelocity\n",
"Energy = 0.5*InitialVelocity*InitialVelocity\n",
"VelocityRange = 10*sqrt(Temperature)\n",
"VelocityStep = 2*VelocityRange/10.\n",
"AverageEnergy = Energy\n",
"AverageEnergy2 = Energy*Energy\n",
"VelocityValues = np.zeros(MCcycles)\n",
"# The Monte Carlo sampling with Metropolis starts here\n",
"for i in range (1, MCcycles, 1):\n",
" TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep\n",
" EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);\n",
" if random.random() <= exp(-beta*EnergyChange):\n",
" CurrentVelocity = TrialVelocity\n",
" Energy += EnergyChange\n",
" VelocityValues[i] = CurrentVelocity\n",
" AverageEnergy += Energy\n",
" AverageEnergy2 += Energy*Energy\n",
"#Final averages\n",
"AverageEnergy = AverageEnergy/MCcycles\n",
"AverageEnergy2 = AverageEnergy2/MCcycles\n",
"Variance = AverageEnergy2 - AverageEnergy*AverageEnergy\n",
"print(AverageEnergy, Variance)\n",
"n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')\n",
"\n",
"plt.xlabel('$v$')\n",
"plt.ylabel('Velocity distribution P(v)')\n",
"plt.title(r'Velocity histogram at $k_BT=2$')\n",
"plt.axis([-5, 5, 0, 600])\n",
"plt.grid(True)\n",
"plt.show()"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}