update on machine learning

This commit is contained in:
mhjensen
2017-12-06 14:13:28 +01:00
parent 2111fd0fbc
commit 3eaf9e4578
70 changed files with 7950 additions and 551 deletions
+129 -55
View File
@@ -10,7 +10,7 @@
"<!-- 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: **Dec 1, 2017**\n",
"Date: **Dec 6, 2017**\n",
"\n",
"Copyright 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -101,16 +101,23 @@
"## Python installers\n",
"If you don't want to perform these operations separately, we recommend two widely used distrubutions which set up \n",
"all relevant dependencies for Python, namely\n",
"1. anaconda\n",
"1. [Anaconda](https://docs.anaconda.com/) 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 **conda**\n",
"\n",
"2. Enthought canopy\n",
"2. [Enthought canopy](https://www.enthought.com/product/canopy/) is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.\n",
"\n",
"## Installing R, C++, cython or Julia\n",
"\n",
"You will also find it convenient to utilize R. Say more about R. \n",
"You will also find it convenient to utilize R. \n",
"Jupyter/Ipython notebook allows you run **R** code interactively in your browser. The software library **R** is \n",
"tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts.\n",
"\n",
"To install **R** with Jupyter notebook [following the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n",
"\n",
"\n",
"\n",
"## Installing R, C++, cython or Julia\n",
"\n",
"\n",
"For the C++ affecianodas, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language \n",
"interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for\n",
"either Python or C++ as programming languages. \n",
@@ -120,18 +127,13 @@
"including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook \n",
"can easily be converted into a nicely rendered **PDF** file or a Latex file for further processing.\n",
"\n",
"This never ends, \n",
"\n",
"If you se the light mark-up language **doconce** you can convert a standard ascii text file into various HTML \n",
"This never ends.\n",
"If you use the light mark-up language **doconce** you can convert a standard ascii text file into various HTML \n",
"formats, ipython notebooks, latex files, pdf files etc. \n",
"\n",
"## Introduction to Jupyter notebook and available tools\n",
"\n",
"## Doing it in R\n",
"Use the Hudson bay model to load data and make plot in R and with python\n",
"\n",
"\n",
"## Representing data, overarching aims"
"## Introduction to Jupyter notebook and available tools"
]
},
{
@@ -157,7 +159,7 @@
"y = np.sin(x)\n",
"plt.plot(x,y,marker='x')\n",
"plt.show()\n",
"data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Roma\", \"Napoli\", \"Torino\", \"Milano\"], 'Age':[51, 21, 34, 45]}\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)"
]
@@ -199,13 +201,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Binning of data\n",
"Use the Hudson bay model to load data and make plot in R and with python\n",
"\n",
"\n",
"\n",
"\n",
"## Adding model complexity: Predator-Prey model from ecology\n",
"## 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",
@@ -228,7 +224,7 @@
"## 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",
"We shall demonstrate the scientific method by\n",
"Here we start by\n",
"\n",
"1. plotting the data\n",
"\n",
@@ -243,11 +239,11 @@
"## Hudson bay data\n",
"\n",
"\n",
"% if FORMAT == 'ipynb':\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",
"% endif\n",
"\n",
"\n",
"<table border=\"1\">\n",
"<thead>\n",
@@ -297,7 +293,7 @@
"from matplotlib import pyplot as plt\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1)\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",
@@ -318,7 +314,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"% if FORMAT != 'ipynb':\n",
"## 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",
@@ -329,11 +324,10 @@
"\n",
"<!-- end figure -->\n",
"\n",
"% endif\n",
"\n",
"\n",
"\n",
"## Why now create a computer model for the hare and lynx populations?\n",
"% if FORMAT == 'ipynb':\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",
@@ -348,7 +342,7 @@
"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",
"% else:\n",
"\n",
" * We see oscillations in the data\n",
"\n",
" * What causes cycles to slow or speed up?\n",
@@ -360,8 +354,6 @@
" * More important: we can understand the ecology dynamics of\n",
" predator-pray populations\n",
"\n",
"% endif\n",
"\n",
"\n",
"\n",
"\n",
@@ -401,25 +393,8 @@
"\n",
"\n",
"\n",
"## The \"new\" discrete bottom-up approach\n",
"\n",
"**The bottom-up approach.**\n",
"\n",
" * Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.\n",
"\n",
" * Where appropriate the students should do the experiment(s) needed to collect the data.\n",
"\n",
" * The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.\n",
"\n",
" * Now we want to increase the understanding through modeling.\n",
"\n",
" * Most of the biology lies in the *derivation* of the model. We shall\n",
" focus on an intuitive discrete approach that leads to difference\n",
" equations that can be programmed *and solved* directly.\n",
"\n",
"\n",
"\n",
"## Basic (computer-friendly) mathematics notation\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",
@@ -459,8 +434,7 @@
"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 and must be accounted for:\n",
"subtracted in the equation for hares:"
"loss of hares must be accounted for. Subtracted in the equation for hares:"
]
},
{
@@ -584,7 +558,7 @@
" H = np.zeros(t.size)\n",
" L = np.zeros(t.size)\n",
"\n",
" print 'Init:', H0, L0, dt\n",
" print('Init:', H0, L0, dt)\n",
" H[0] = H0\n",
" L[0] = L0\n",
"\n",
@@ -594,7 +568,7 @@
" return H, L, t\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1)\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",
@@ -621,7 +595,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"% if FORMAT != 'ipynb':\n",
"## The plot\n",
"\n",
"<!-- dom:FIGURE: [fig/Hudson_Bay_sim.png, width=700 frac=0.9] -->\n",
@@ -633,9 +606,110 @@
"<!-- end figure -->\n",
"\n",
"\n",
"% else:\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",
"% endif"
"\n",
"\n",
"## Linear regression in Python"
]
},
{
"cell_type": "code",
"execution_count": 5,
"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": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"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\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Non-Linear Least squares in R"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"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)"
]
}
],