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
+109 -53
View File
@@ -86,17 +86,25 @@ etc etc.
===== Python installers =====
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
o anaconda
o Enthought canopy
o "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_
o "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.
!split
===== Installing R, C++, cython or Julia =====
You will also find it convenient to utilize R. Say more about R.
You will also find it convenient to utilize R.
Jupyter/Ipython notebook allows you run _R_ code interactively in your browser. The software library _R_ is
tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts.
To install _R_ with Jupyter notebook "following the link here":"https://mpacer.org/maths/r-kernel-for-ipython-notebook"
!split
===== Installing R, C++, cython or Julia =====
For the C++ affecianodas, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language
interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for
either Python or C++ as programming languages.
@@ -106,21 +114,15 @@ setup allows you to integrate widely popular softwares and tools for scientific
including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook
can easily be converted into a nicely rendered _PDF_ file or a Latex file for further processing.
This never ends,
If you se the light mark-up language _doconce_ you can convert a standard ascii text file into various HTML
This never ends.
If you use the light mark-up language _doconce_ you can convert a standard ascii text file into various HTML
formats, ipython notebooks, latex files, pdf files etc.
!split
===== Introduction to Jupyter notebook and available tools =====
!split
===== Doing it in R =====
Use the Hudson bay model to load data and make plot in R and with python
!split
===== Representing data, overarching aims =====
!bblock
!bc pycod
import numpy as np
@@ -136,14 +138,12 @@ x = np.linspace(-10,10,100)
y = np.sin(x)
plt.plot(x,y,marker='x')
plt.show()
data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Roma", "Napoli", "Torino", "Milano"], 'Age':[51, 21, 34, 45]}
data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
data_pandas = pd.DataFrame(data)
display(data_pandas)
!ec
!eblock
!split
===== Representing data, more examples =====
!bblock
@@ -167,16 +167,8 @@ plt.show()
!ec
!eblock
!split
===== Binning of data =====
Use the Hudson bay model to load data and make plot in R and with python
Use LSQ first, then neural networks with R and scikt-learn
!split
===== Adding model complexity: Predator-Prey model from ecology =====
===== Predator-Prey model from ecology =====
!bblock
The population dynamics of a simple predator-prey system is a
@@ -197,7 +189,7 @@ scientific method:
!bblock
Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why?
We shall demonstrate the scientific method by
Here we start by
o plotting the data
o derive a simple model for the population dynamics
@@ -210,11 +202,11 @@ We shall demonstrate the scientific method by
!bblock
% if FORMAT == 'ipynb':
Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle.
One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920.
% endif
|------------------------------------------------------|
| Year | Hares (x1000) | Lynx (x1000)|
@@ -253,18 +245,16 @@ One reason that this particular system has been so extensively studied is that t
@@@CODE src/plot_Hudson.py
!eblock
% if FORMAT != 'ipynb':
!split
===== Hares and lynx in Hudson bay from 1900 to 1920 =====
FIGURE: [fig/Hudson_Bay_data, width=700 frac=0.9]
% endif
!split
===== Why now create a computer model for the hare and lynx populations? =====
!bblock
% if FORMAT == 'ipynb':
We see from the plot that there are indeed fluctuations.
We would like to create a mathematical model that explains these
population fluctuations. Ecologists have predicted that in a simple
@@ -279,14 +269,13 @@ this? What causes cycles to slow or speed up? What affects the
amplitude of the oscillation or do you expect to see the oscillations
damp to a stable equilibrium? The models tend to ignore factors like
climate and other complicating factors. How significant are these?
% else:
* We see oscillations in the data
* 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?
* With a model we can better *understand the data*
* More important: we can understand the ecology dynamics of
predator-pray populations
% endif
!eblock
@@ -315,23 +304,9 @@ ODEs* (which cannot be solved)
!eblock
!split
===== The ``new'' discrete bottom-up approach =====
!bblock The bottom-up approach
!bpop
* 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.
* Where appropriate the students should do the experiment(s) needed to collect the data.
* 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.
* Now we want to increase the understanding through modeling.
* Most of the biology lies in the *derivation* of the model. We shall
focus on an intuitive discrete approach that leads to difference
equations that can be programmed *and solved* directly.
!epop
!eblock
!split
===== Basic (computer-friendly) mathematics notation =====
===== Basic mathematics notation =====
!bblock
* Time points: $t_0,t_1,\ldots,t_m$
* Uniform distribution of time points: $t_n=n\Delta t$
@@ -360,8 +335,7 @@ $H\cdot L$ pairs in total. When such pairs meet during a time
interval $\Delta t$, there is some
small probablity that the lynx will eat the hare.
So in fraction $b\Delta t HL$, the lynx eat hares. This
loss of hares and must be accounted for:
subtracted in the equation for hares:
loss of hares must be accounted for. Subtracted in the equation for hares:
!bt
\[ \Delta H = a\Delta t H^n - b \Delta t H^nL^n\]
@@ -433,15 +407,97 @@ Note:
@@@CODE src/Hudson_Bay.py
!eblock
% if FORMAT != 'ipynb':
!split
===== The plot =====
FIGURE: [fig/Hudson_Bay_sim, width=700 frac=0.9]
% else:
If we perform a least-square fitting, we can find optimal values for the parameters $a$, $b$, $d$, $c$. The optimal parameters are $a=0.4807$, $b=0.02482$, $d=0.9272$ and $c=0.02756$. These parameters result in a slightly modified initial conditions, namely $H(0) = 34.91$ and $L(0)=3.857$. With these parameters we are now ready to solve the equations and plot these data together with the experimental values.
% endif
!split
===== Linear regression in Python =====
!bblock
!bc pycod
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
x = data[:,0]
y = data[:,1]
line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)
reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))
plt.plot(line, reg.predict(line), label="decision tree")
regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))
plt.plot(line, regline.predict(line), label= "Linear Regression")
plt.plot(x, y, label= "Linear Regression")
plt.show()
!ec
!eblock
!split
===== Linear Least squares in R =====
!bblock
!bc pycod
HudsonBay = read.csv("src/Hudson_Bay.csv",header=T)
fix(HudsonBay)
dim(HudsonBay)
names(HudsonBay)
plot(HudsonBay$Year, HudsonBay$Hares..x1000.)
attach(HudsonBay)
plot(Year, Hares..x1000.)
plot(Year, Hares..x1000., col="red", varwidth=T, xlab="Years", ylab="Haresx 1000")
summary(HudsonBay)
summary(Hares..x1000.)
library(MASS)
library(ISLR)
scatter.smooth(x=Year, y = Hares..x1000.)
linearMod = lm(Hares..x1000. ~ Year)
print(linearMod)
summary(linearMod)
plot(linearMod)
confint(linearMod)
predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval="confidence")
!ec
!eblock
!split
===== Non-Linear Least squares in R =====
!bblock
!bc pycod
set.seed(1485)
len = 24
x = runif(len)
y = x^3+rnorm(len, 0,0.06)
ds = data.frame(x = x, y = y)
str(ds)
plot( y ~ x, main ="Known cubic with noise")
s = seq(0,1,length =100)
lines(s, s^3, lty =2, col ="green")
m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)
class(m)
summary(m)
power = round(summary(m)$coefficients[1], 3)
power.se = round(summary(m)$coefficients[2], 3)
plot(y ~ x, main = "Fitted power model", sub = "Blue: fit; green: known")
s = seq(0, 1, length = 100)
lines(s, s^3, lty = 2, col = "green")
lines(s, predict(m, list(x = s)), lty = 1, col = "blue")
text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4)
!ec
!eblock