diff --git a/doc/pub/How2ReadData/html/How2ReadData-bs.html b/doc/pub/How2ReadData/html/How2ReadData-bs.html index d8e1b1bda..fc1b28984 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-bs.html +++ b/doc/pub/How2ReadData/html/How2ReadData-bs.html @@ -44,67 +44,52 @@ Automatically generated HTML file from DocOnce source ('Software and needed installations', 2, None, '___sec1'), ('Python installers', 2, None, '___sec2'), ('Installing R, C++, cython or Julia', 2, None, '___sec3'), - ('Installing R, C++, cython or Julia', 2, None, '___sec4'), - ('Introduction to Jupyter notebook and available tools', + ('Installing R, C++, cython, Numba etc', 2, None, '___sec4'), + ('Simple linear regression model using _scikit-learn_', 2, None, '___sec5'), - ('Representing data, more examples', 2, None, '___sec6'), - ('Simple regression model', 2, None, '___sec7'), - ('Simple regression model, now using _scikit-learn_', - 2, - None, - '___sec8'), - ('Simple regression model with gradient descent', - 2, - None, - '___sec9'), - ('Simple regression model with stochastic gradient descent', - 2, - None, - '___sec10'), - ('Polynomial regression', 2, None, '___sec11'), - ('Predator-Prey model from ecology', 2, None, '___sec12'), - ('Case study from Hudson bay', 2, None, '___sec13'), - ('Hudson bay data', 2, None, '___sec14'), - ('Plotting the data', 2, None, '___sec15'), + ('Predator-Prey model from ecology', 2, None, '___sec6'), + ('Case study from Hudson bay', 2, None, '___sec7'), + ('Hudson bay data', 2, None, '___sec8'), + ('Plotting the data', 2, None, '___sec9'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec16'), + '___sec10'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec17'), - ('The traditional (top-down) approach', 2, None, '___sec18'), - ('Basic mathematics notation', 2, None, '___sec19'), + '___sec11'), + ('The traditional (top-down) approach', 2, None, '___sec12'), + ('Basic mathematics notation', 2, None, '___sec13'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), + '___sec14'), + ('Basic dynamics of the population of lynx', 2, None, '___sec15'), + ('Evolution equations', 2, None, '___sec16'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec17'), + ('The program', 2, None, '___sec18'), + ('The plot', 2, None, '___sec19'), + ('Linear regression in Python', 2, None, '___sec20'), + ('Linear Least squares in R', 2, None, '___sec21'), + ('Non-Linear Least squares in R', 2, None, '___sec22'), + ('Example: ecoli lab experiment', 2, None, '___sec23'), ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25'), - ('Linear regression in Python', 2, None, '___sec26'), - ('Linear Least squares in R', 2, None, '___sec27'), - ('Non-Linear Least squares in R', 2, None, '___sec28'), - ('Example: ecoli lab experiment', 2, None, '___sec29'), - ('The program', 2, None, '___sec30'), - ('The output', 2, None, '___sec31'), - ('Parameter estimation', 2, None, '___sec32'), + ('The output', 2, None, '___sec25'), + ('Parameter estimation', 2, None, '___sec26'), ('A program relevant for the biological problem', 2, None, - '___sec33'), - ('Simulating financial transcations', 2, None, '___sec34'), - ('Simulation of Transactions', 3, None, '___sec35'), + '___sec27'), + ('Simulating financial transactions', 2, None, '___sec28'), + ('Simulation of Transactions', 3, None, '___sec29'), ('Particle in one dimension an velocity distribution', 2, None, - '___sec36')]} + '___sec30')]} end of tocinfo --> @@ -146,39 +131,33 @@ MathJax.Hub.Config({
  • Software and needed installations
  • Python installers
  • Installing R, C++, cython or Julia
  • -
  • Installing R, C++, cython or Julia
  • -
  • Introduction to Jupyter notebook and available tools
  • -
  • Representing data, more examples
  • -
  • Simple regression model
  • -
  • Simple regression model, now using scikit-learn
  • -
  • Simple regression model with gradient descent
  • -
  • Simple regression model with stochastic gradient descent
  • -
  • Polynomial regression
  • -
  • Predator-Prey model from ecology
  • -
  • Case study from Hudson bay
  • -
  • Hudson bay data
  • -
  • Plotting the data
  • -
  • Hares and lynx in Hudson bay from 1900 to 1920
  • -
  • Why now create a computer model for the hare and lynx populations?
  • -
  • The traditional (top-down) approach
  • -
  • Basic mathematics notation
  • -
  • Basic dynamics of the population of hares
  • -
  • Basic dynamics of the population of lynx
  • -
  • Evolution equations
  • -
  • Adapt the model to the Hudson Bay case
  • +
  • Installing R, C++, cython, Numba etc
  • +
  • Simple linear regression model using scikit-learn
  • +
  • Predator-Prey model from ecology
  • +
  • Case study from Hudson bay
  • +
  • Hudson bay data
  • +
  • Plotting the data
  • +
  • Hares and lynx in Hudson bay from 1900 to 1920
  • +
  • Why now create a computer model for the hare and lynx populations?
  • +
  • The traditional (top-down) approach
  • +
  • Basic mathematics notation
  • +
  • Basic dynamics of the population of hares
  • +
  • Basic dynamics of the population of lynx
  • +
  • Evolution equations
  • +
  • Adapt the model to the Hudson Bay case
  • +
  • The program
  • +
  • The plot
  • +
  • Linear regression in Python
  • +
  • Linear Least squares in R
  • +
  • Non-Linear Least squares in R
  • +
  • Example: ecoli lab experiment
  • The program
  • -
  • The plot
  • -
  • Linear regression in Python
  • -
  • Linear Least squares in R
  • -
  • Non-Linear Least squares in R
  • -
  • Example: ecoli lab experiment
  • -
  • The program
  • -
  • The output
  • -
  • Parameter estimation
  • -
  • A program relevant for the biological problem
  • -
  • Simulating financial transcations
  • -
  •    Simulation of Transactions
  • -
  • Particle in one dimension an velocity distribution
  • +
  • The output
  • +
  • Parameter estimation
  • +
  • A program relevant for the biological problem
  • +
  • Simulating financial transactions
  • +
  •    Simulation of Transactions
  • +
  • Particle in one dimension an velocity distribution
  • @@ -212,7 +191,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    May 22, 2018

    +

    May 26, 2018


    @@ -223,28 +202,38 @@ MathJax.Hub.Config({

    Introduction

    -Before we proceed 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. - -

    -Our emphasis here is on understanding the mathematical aspects of -different algorithms, however, where possible we will emphasize the +Our emphasis throughout this series of lectures +is on understanding the mathematical aspects of +different algorithms used in the fields of data analysis and machine learning. +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 +and top-down approach to 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 +algorithms themselves. The examples we will use in the beginning, start with simple +polynomials with random noise added, and using the Python software package Scikit-learn we -will introduce various machine learning algorithm s to make fits of -the data data and predictions. We move thereafter to more interesting +will introduce various machine learning algorithms to make fits of +the 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 scikit-learn. 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. +then use machine learning algorithms included in for example +scikit-learn. 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. + +

    +All these examples will serve us the purpose of getting us started, furthermore, they +allow us to catch more than two birds with a stone. They will allow us +to bring in some programming specific topics and tools as well as +showing the power of various Python (and R) packages for machine +learning and statistical data analysis. In the lectures on linear +algebra we cover in more detail various programming features of languages like Python and C++ (and other), we will also look into more specific linear functions which +are relevant for the various algorithms we will discuss. Here, we will +mainly focus on two specific Python packages for Machine Learning, +scikit-learn and tensorflow (see below for links etc). +Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming.

    @@ -252,29 +241,30 @@ Finally, our last example consists of economic data from the OECD.

    Software and needed installations

    -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 R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. +We will make extensive use of Python as programming language and its +myriad of available libraries. Furthermore, you will find +IPython/Jupyter notebooks invaluable in your work. You can run R +codes in the Jupyter/IPython notebooks, with the immediate benefit of +visualizing your data. You can also use compiled languages like C++, +Rust, Fortran etc if you prefer. The focus in these lectures will be +on Python, but we will provide many code examples for those of you who +prefer R or compiled languages. You can integrate C++ codes and R in for example +a Jupyter notebook.

    -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 pip as - -

      -
    1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
    2. -
    - -For Python3, replace pip with pip3. +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 pip as o pip install +numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas +pillow For Python3, replace pip with pip3.

    -For OSX users we recommend also, after having installed Xcode, to install brew. Brew allows -for a seamless installation of additional software via for example +For OSX users we recommend also, after having installed Xcode, to +install brew. Brew allows for a seamless installation of additional +software via for example o brew install python3 -

      -
    1. brew install python3
    2. -
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +

    +For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, you can use pip as well and simply install Python as

      @@ -287,54 +277,268 @@ 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 -
        -
      1. Anaconda 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
      2. -
      3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
      4. -
      +

      +If you don't want to perform these operations separately and venture +into the hassle of exploring how to set up dependencies and paths, we +recommend two widely used distrubutions which set up all relevant +dependencies for Python, namely o +Anaconda, which 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 is a Python +distribution for scientific and analytic computing distribution and +analysis environment, available for free and under a commercial +license. +

      Installing R, C++, cython or Julia

      -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. +You will also find it convenient to utilize R. Although we will mainly +use Python during lectures and in various projects and exercises, we +provide a full R set of codes for the same examples. Those of you +already familiar with R should feel free to continue using R, keeping +however an eye on the parallel Python set ups. Similarly, if you are a +Python afecionado, feel free to explore R as well. Jupyter/Ipython +notebook allows you to run R codes 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 +To install R with Jupyter notebook following the link +here

      -

      Installing R, C++, cython or Julia

      +

      Installing R, C++, cython, Numba etc

      -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. +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++ (or Fortran or other compiled languages) as programming +languages.

      -To add more entropy, cython 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 PDF file or a Latex file for further processing. For example, convert to latex as +To add more entropy, cython 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. Similarly, the +Numba Python package delivers increased performance +capabilities with minimal rewrites of your codes. With its +versatility, 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. For example, convert to latex as +

      + + +

      pycod jupyter nbconvert filename.ipynb --to latex 
      +
      +

      +And to add more versatility, symbolic Python package SymPy is Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. + +

      +Finally, if you wish to 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 with minimal edits. + +

      + + +

      Simple linear regression model using scikit-learn

      +We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. +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. + +

      +The Numpy functions are imported used the import numpy as np +statement and the random number generator for the uniform distribution +is called using the function np.random.rand(), where we specificy +that we want \( 100 \) random variables. Using Numpy we define +automatically an array with the specified number of elements, \( 100 \) in +our case. With the Numpy function randn() we can compute random +numbers with the normal distribution (mean value \( \mu \) equal to zero and +variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear +dependence as function of \( x \) + +$$ +y = 2x+N(0,1), +$$ + +

      +where \( N(0,1) \) represents random numbers generated by the normal +distribution. From scikit-learn we import then the +LinearRegression functionality and make a prediction \( \tilde{y} = +\alpha + \beta x \) using the function fit(x,y). We call the set of +data \( (\hat{x},\hat{y}) \) for our training data. The Python package +scikit-learn has also a functionality which extracts the above +fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will +distinguish between training data and test data. + +

      +For plotting we use the Python package +matplotlib which produces publication +quality figures. Feel free to explore the extensive +gallery of examples. In +this example we plot our original values of \( x \) and \( y \) as well as the +prediction ypredict (\( \tilde{y} \)), which attempts at fitting our +data with a straight line. + +

      +The Python follows here.

      -

      jupyter nbconvert filename.ipynb --to latex
      +
      # Importing various packages
      +import numpy as np
      +import matplotlib.pyplot as plt
      +from sklearn.linear_model import LinearRegression
      +
      +x = np.random.rand(100,1)
      +y = 2*x+np.random.randn(100,1)
      +linreg = LinearRegression()
      +linreg.fit(x,y)
      +xnew = np.array([[0],[1]])
      +ypredict = linreg.predict(xnew)
      +
      +plt.plot(xnew, ypredict, "r-")
      +plt.plot(x, y ,'ro')
      +plt.axis([0,1.0,0, 5.0])
      +plt.xlabel(r'$x$')
      +plt.ylabel(r'$y$')
      +plt.title(r'Simple Linear Regression')
      +plt.show()
       

      -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. +This example serves several aims. It allows us to demonstrate several +aspects of data analysis and later machine learning algorithms. The +immediate visualization shows that our linear fit is not +impressive. It goes through the data points, but there are many +outliers which are not reproduced by our linear regression. We could +now play around with this small program and change for example the +factor in front of \( x \) and the normal distribution. Try to change the +function \( y \) to + +$$ +y = 10x+0.01N(0,1), +$$

      - +where \( x \) is defined as before. Does the fit look better? Indeed, by +reducing the role of the normal distribution we see immediately that +our linear prediction seemingly reproduces better the training +set. However, this testing 'by the eye' is obviouly not satisfactory in the +long run. Here we have only defined the training data and our model, and +have not discussed a more rigorous approach to the cost function. -

      Introduction to Jupyter notebook and available tools

      +

      +We need more rigorous criteria in defining whether we have succeed or +not in modeling our training data. You will be surprised to see that +many scientists seldomly venture beyond this 'by the eye' approach. A +standard approach for the cost function is the so-called \( \chi^2 \) +function + +$$ \chi^2 = \frac{1}{n} +\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, +$$ + +

      +where \( \sigma_i^2 \) is the variance (to be defined later) of the entry +\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves +however the aim of scaling the equations and make the cost function +dimensionless. + +

      +Minimizing the cost function is a central aspect of +our discussions to come. Finding its minima as function of the model +parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring +theme in these series of lectures. Essentially all machine learning +algorithms we will discuss center around the minimization of the +chosen cost function. This depends in turn on our specific +model for describing the data, a typical situation in supervised +learning. Automatizing the search for the minima of the cost function is a +central ingredient in all algorithms. Typical methods which are +employed are various variants of gradient methods. These will be +discussed in more detail later. Again, you'll be surprised to hear that +many practitioners minimize the above function ''by the eye', popularly dubbed as +'chi by the eye'. That is, change a parameter and see (visually and numerically) that +the your \( \chi^2 \) function becomes smaller. + +

      +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 +the relative error as +$$ +\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. +$$ + +We can modify easily the above Python code and plot the relative instead +

      + + +

      import numpy as np
      +import matplotlib.pyplot as plt
      +from sklearn.linear_model import LinearRegression
      +
      +x = np.random.rand(100,1)
      +y = 5*x+0.01*np.random.randn(100,1)
      +linreg = LinearRegression()
      +linreg.fit(x,y)
      +ypredict = linreg.predict(x)
      +
      +plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
      +plt.axis([0,1.0,0.0, 0.5])
      +plt.xlabel(r'$x$')
      +plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
      +plt.title(r'Relative error')
      +plt.show()
      +
      +

      +Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. + +

      +As mentioned above, scikit-learn has an impressive functionality. +We can for example extract the values of \( \alpha \) and \( \beta \) and their error estimates, +or the variance and standard deviation and many other properties from the statistical data analysis. Here we show an example of the functionality of scikit-learn. +

      + + +

      import numpy as np
      +import matplotlib.pyplot as plt
      +from sklearn.linear_model import LinearRegression
      +from sklearn.metrics import mean_squared_error, r2_score
      +
      +x = np.random.rand(100,1)
      +y = 2*x+np.random.randn(100,1)
      +linreg = LinearRegression()
      +linreg.fit(x,y)
      +ypredict = linreg.predict(x)
      +print('Coefficients: \n', linreg.coef_)
      +# The mean squared error                               
      +print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
      +# Explained variance score: 1 is perfect prediction                                 
      +print('Variance score: %.2f' % r2_score(y, ypredict))
      +plt.plot(x, ypredict, "r-")
      +plt.plot(x, y ,'ro')
      +plt.axis([0,1.0,0, 5.0])
      +plt.xlabel(r'$x$')
      +plt.ylabel(r'$y$')
      +plt.title(r'Linear Regression fit ')
      +plt.show()
      +
      +

      +We will come to the definition of these outputs later. + +

      +Another useful Python package is +pandas, which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. The following simple example shows an example on 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.

      @@ -368,176 +572,7 @@ display(data_pandas)

      -

      Representing data, more examples

      -
      -
      -

      -

      - - -

      import numpy as np
      -import matplotlib.pyplot as plt
      -from scipy import sparse
      -import pandas as pd
      -from IPython.display import display
      -import mglearn
      -import sklearn
      -from sklearn.linear_model import LinearRegression
      -from sklearn.tree import DecisionTreeRegressor
      -x, y = mglearn.datasets.make_wave(n_samples=100)
      -line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1)
      -reg = DecisionTreeRegressor(min_samples_split=3).fit(x,y)
      -plt.plot(line, reg.predict(line), label="decision tree")
      -regline = LinearRegression().fit(x,y)
      -plt.plot(line, regline.predict(line), label= "Linear Regression")
      -plt.show()
      -
      -

      -

      -
      - - -

      - - -

      Simple regression model

      -Add info about the equations -

      - - -

      # Importing various packages
      -from random import random, seed
      -import numpy as np
      -import matplotlib.pyplot as plt
      -
      -x = 2*np.random.rand(100,1)
      -y = 4+3*x+np.random.randn(100,1)
      -
      -xb = np.c_[np.ones((100,1)), x]
      -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
      -xnew = np.array([[0],[2]])
      -xbnew = np.c_[np.ones((2,1)), xnew]
      -ypredict = xbnew.dot(theta)
      -
      -plt.plot(xnew, ypredict, "r-")
      -plt.plot(x, y ,'ro')
      -plt.axis([0,2.0,0, 15.0])
      -plt.xlabel(r'$x$')
      -plt.ylabel(r'$y$')
      -plt.title(r'Linear Regression')
      -plt.show()
      -
      -

      - - -

      Simple regression model, now using scikit-learn

      -Add info about the equations -

      - - -

      # Importing various packages
      -from random import random, seed
      -import numpy as np
      -import matplotlib.pyplot as plt
      -from sklearn.linear_model import LinearRegression
      -
      -x = 2*np.random.rand(100,1)
      -y = 4+3*x+np.random.randn(100,1)
      -linreg = LinearRegression()
      -linreg.fit(x,y)
      -xnew = np.array([[0],[2]])
      -ypredict = linreg.predict(xnew)
      -
      -plt.plot(xnew, ypredict, "r-")
      -plt.plot(x, y ,'ro')
      -plt.axis([0,2.0,0, 15.0])
      -plt.xlabel(r'$x$')
      -plt.ylabel(r'$y$')
      -plt.title(r'Random numbers ')
      -plt.show()
      -
      -

      - - -

      Simple regression model with gradient descent

      -Add info about the equations, play around with different learning rates -

      - - -

      # Importing various packages
      -from math import exp, sqrt
      -from random import random, seed
      -import numpy as np
      -import matplotlib.pyplot as plt
      -
      -x = 2*np.random.rand(100,1)
      -y = 4+3*x+np.random.randn(100,1)
      -
      -xb = np.c_[np.ones((100,1)), x]
      -theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
      -print(theta_linreg)
      -theta = np.random.randn(2,1)
      -
      -eta = 0.1
      -Niterations = 1000
      -m = 100
      -
      -for iter in range(Niterations):
      -    gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)
      -    theta -= eta*gradients
      -
      -print(theta)
      -xnew = np.array([[0],[2]])
      -xbnew = np.c_[np.ones((2,1)), xnew]
      -ypredict = xbnew.dot(theta)
      -ypredict2 = xbnew.dot(theta_linreg)
      -plt.plot(xnew, ypredict, "r-")
      -plt.plot(xnew, ypredict2, "b-")
      -plt.plot(x, y ,'ro')
      -plt.axis([0,2.0,0, 15.0])
      -plt.xlabel(r'$x$')
      -plt.ylabel(r'$y$')
      -plt.title(r'Random numbers ')
      -plt.show()
      -
      -

      - - -

      Simple regression model with stochastic gradient descent

      -Add info about the equations, play around with different learning rates -

      - - -

      # Importing various packages
      -from math import exp, sqrt
      -from random import random, seed
      -import numpy as np
      -import matplotlib.pyplot as plt
      -from sklearn.linear_model import SGDRegressor
      -
      -x = 2*np.random.rand(100,1)
      -y = 4+3*x+np.random.randn(100,1)
      -
      -xb = np.c_[np.ones((100,1)), x]
      -theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
      -print(theta_linreg)
      -sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
      -sgdreg.fit(x,y.ravel())
      -print(sgdreg.intercept_, sgdreg.coef_)
      -
      -

      - - -

      Polynomial regression

      -

      - - -

      
      -
      -

      - - -

      Predator-Prey model from ecology

      +

      Predator-Prey model from ecology

      @@ -562,7 +597,7 @@ scientific method:

      -

      Case study from Hudson bay

      +

      Case study from Hudson bay

      @@ -584,7 +619,7 @@ Here we start by

      -

      Hudson bay data

      +

      Hudson bay data

      @@ -639,7 +674,7 @@ One reason that this particular system has been so extensively studied is that t

      -

      Plotting the data

      +

      Plotting the data

      @@ -676,7 +711,7 @@ plt.show()

      -

      Hares and lynx in Hudson bay from 1900 to 1920

      +

      Hares and lynx in Hudson bay from 1900 to 1920





      @@ -684,7 +719,7 @@ plt.show()

      -

      Why now create a computer model for the hare and lynx populations?

      +

      Why now create a computer model for the hare and lynx populations?

      @@ -718,7 +753,7 @@ climate and other complicating factors. How significant are these?

      -

      The traditional (top-down) approach

      +

      The traditional (top-down) approach

      @@ -752,7 +787,7 @@ ODEs (which cannot be solved)

      -

      Basic mathematics notation

      +

      Basic mathematics notation

      @@ -773,7 +808,7 @@ ODEs (which cannot be solved)

      -

      Basic dynamics of the population of hares

      +

      Basic dynamics of the population of hares

      @@ -802,7 +837,7 @@ $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$

      -

      Basic dynamics of the population of lynx

      +

      Basic dynamics of the population of lynx

      @@ -833,7 +868,7 @@ $$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$

      -

      Evolution equations

      +

      Evolution equations

      @@ -863,7 +898,7 @@ Note:

      -

      Adapt the model to the Hudson Bay case

      +

      Adapt the model to the Hudson Bay case

      @@ -887,7 +922,7 @@ Note:

      -

      The program

      +

      The program

      @@ -948,7 +983,7 @@ plt.show()

      -

      The plot

      +

      The plot





      @@ -959,7 +994,7 @@ If we perform a least-square fitting, we can find optimal values for the paramet

      -

      Linear regression in Python

      +

      Linear regression in Python

      @@ -993,7 +1028,7 @@ plt.show()

      -

      Linear Least squares in R

      +

      Linear Least squares in R

      @@ -1028,7 +1063,7 @@ predict(linearMod,data.frame(Year -

      Non-Linear Least squares in R

      +

      Non-Linear Least squares in R

      @@ -1063,7 +1098,7 @@ text(0, 0.5 -

      Example: ecoli lab experiment

      +

      Example: ecoli lab experiment

      @@ -1101,7 +1136,7 @@ The population grows faster and faster. The program +

      The program

      @@ -1135,7 +1170,7 @@ r = 0.5 % if FORMAT != 'ipynb': -

      The output

      +

      The output

      @@ -1167,7 +1202,7 @@ N[20]=86.7

      -

      Parameter estimation

      +

      Parameter estimation

      @@ -1197,7 +1232,7 @@ Use experimental data in the fraction, say \( t_1=600 \), \( t_2=1200 \),

      -

      A program relevant for the biological problem

      +

      A program relevant for the biological problem

      @@ -1246,7 +1281,7 @@ Change r in the program and play around to make a better fit!

      -

      Simulating financial transcations

      +

      Simulating financial transactions

      The aim here is to simulate financial transactions among financial agents @@ -1320,7 +1355,7 @@ exponentially decreases with \( m' \). 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). -

      Simulation of Transactions

      +

      Simulation of Transactions

      Our task is to first set up an algorithm which simulates the above transactions with an initial amount \( m_0 \). @@ -1453,7 +1488,7 @@ where \( c_{ij} \) represents the number of previous interactions that have tak

      -

      Particle in one dimension an velocity distribution

      +

      Particle in one dimension an velocity distribution

      diff --git a/doc/pub/How2ReadData/html/How2ReadData-reveal.html b/doc/pub/How2ReadData/html/How2ReadData-reveal.html index 10f15e993..370fc5239 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-reveal.html +++ b/doc/pub/How2ReadData/html/How2ReadData-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({

      [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

       
      -

      May 22, 2018

      +

      May 26, 2018


      @@ -162,28 +162,38 @@ MathJax.Hub.Config({

      Introduction

      -Before we proceed 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. - -

      -Our emphasis here is on understanding the mathematical aspects of -different algorithms, however, where possible we will emphasize the +Our emphasis throughout this series of lectures +is on understanding the mathematical aspects of +different algorithms used in the fields of data analysis and machine learning. +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 +and top-down approach to 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 +algorithms themselves. The examples we will use in the beginning, start with simple +polynomials with random noise added, and using the Python software package Scikit-learn we -will introduce various machine learning algorithm s to make fits of -the data data and predictions. We move thereafter to more interesting +will introduce various machine learning algorithms to make fits of +the 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 scikit-learn. 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. +then use machine learning algorithms included in for example +scikit-learn. 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. + +

      +All these examples will serve us the purpose of getting us started, furthermore, they +allow us to catch more than two birds with a stone. They will allow us +to bring in some programming specific topics and tools as well as +showing the power of various Python (and R) packages for machine +learning and statistical data analysis. In the lectures on linear +algebra we cover in more detail various programming features of languages like Python and C++ (and other), we will also look into more specific linear functions which +are relevant for the various algorithms we will discuss. Here, we will +mainly focus on two specific Python packages for Machine Learning, +scikit-learn and tensorflow (see below for links etc). +Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming. @@ -191,31 +201,30 @@ Finally, our last example consists of economic data from the OECD.

      Software and needed installations

      -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 R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. +We will make extensive use of Python as programming language and its +myriad of available libraries. Furthermore, you will find +IPython/Jupyter notebooks invaluable in your work. You can run R +codes in the Jupyter/IPython notebooks, with the immediate benefit of +visualizing your data. You can also use compiled languages like C++, +Rust, Fortran etc if you prefer. The focus in these lectures will be +on Python, but we will provide many code examples for those of you who +prefer R or compiled languages. You can integrate C++ codes and R in for example +a Jupyter notebook.

      -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 pip as - -

        -

      1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
      2. -
      -

      - -For Python3, replace pip with pip3. +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 pip as o pip install +numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas +pillow For Python3, replace pip with pip3.

      -For OSX users we recommend also, after having installed Xcode, to install brew. Brew allows -for a seamless installation of additional software via for example +For OSX users we recommend also, after having installed Xcode, to +install brew. Brew allows for a seamless installation of additional +software via for example o brew install python3 -

        -

      1. brew install python3
      2. -

      - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, you can use pip as well and simply install Python as

        @@ -229,13 +238,21 @@ 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 -
          -

        1. Anaconda 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
        2. -

        3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
        4. -
        +

        +If you don't want to perform these operations separately and venture +into the hassle of exploring how to set up dependencies and paths, we +recommend two widely used distrubutions which set up all relevant +dependencies for Python, namely o +Anaconda, which 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 is a Python +distribution for scientific and analytic computing distribution and +analysis environment, available for free and under a commercial +license.

        @@ -243,41 +260,254 @@ all relevant dependencies for Python, namely

        Installing R, C++, cython or Julia

        -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. +You will also find it convenient to utilize R. Although we will mainly +use Python during lectures and in various projects and exercises, we +provide a full R set of codes for the same examples. Those of you +already familiar with R should feel free to continue using R, keeping +however an eye on the parallel Python set ups. Similarly, if you are a +Python afecionado, feel free to explore R as well. Jupyter/Ipython +notebook allows you to run R codes 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 +To install R with Jupyter notebook following the link +here

        -

        Installing R, C++, cython or Julia

        +

        Installing R, C++, cython, Numba etc

        -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. +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++ (or Fortran or other compiled languages) as programming +languages.

        -To add more entropy, cython 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 PDF file or a Latex file for further processing. For example, convert to latex as +To add more entropy, cython 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. Similarly, the +Numba Python package delivers increased performance +capabilities with minimal rewrites of your codes. With its +versatility, 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. For example, convert to latex as +

        + + +

        pycod jupyter nbconvert filename.ipynb --to latex 
        +
        +

        +And to add more versatility, symbolic Python package SymPy is Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. + +

        +Finally, if you wish to 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 with minimal edits. +

        + + +
        +

        Simple linear regression model using scikit-learn

        +We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. +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. + +

        +The Numpy functions are imported used the import numpy as np +statement and the random number generator for the uniform distribution +is called using the function np.random.rand(), where we specificy +that we want \( 100 \) random variables. Using Numpy we define +automatically an array with the specified number of elements, \( 100 \) in +our case. With the Numpy function randn() we can compute random +numbers with the normal distribution (mean value \( \mu \) equal to zero and +variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear +dependence as function of \( x \) + +

         
        +$$ +y = 2x+N(0,1), +$$ +

         
        + +

        +where \( N(0,1) \) represents random numbers generated by the normal +distribution. From scikit-learn we import then the +LinearRegression functionality and make a prediction \( \tilde{y} = +\alpha + \beta x \) using the function fit(x,y). We call the set of +data \( (\hat{x},\hat{y}) \) for our training data. The Python package +scikit-learn has also a functionality which extracts the above +fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will +distinguish between training data and test data. + +

        +For plotting we use the Python package +matplotlib which produces publication +quality figures. Feel free to explore the extensive +gallery of examples. In +this example we plot our original values of \( x \) and \( y \) as well as the +prediction ypredict (\( \tilde{y} \)), which attempts at fitting our +data with a straight line. + +

        +The Python follows here.

        -

        jupyter nbconvert filename.ipynb --to latex
        +
        # Importing various packages
        +import numpy as np
        +import matplotlib.pyplot as plt
        +from sklearn.linear_model import LinearRegression
        +
        +x = np.random.rand(100,1)
        +y = 2*x+np.random.randn(100,1)
        +linreg = LinearRegression()
        +linreg.fit(x,y)
        +xnew = np.array([[0],[1]])
        +ypredict = linreg.predict(xnew)
        +
        +plt.plot(xnew, ypredict, "r-")
        +plt.plot(x, y ,'ro')
        +plt.axis([0,1.0,0, 5.0])
        +plt.xlabel(r'$x$')
        +plt.ylabel(r'$y$')
        +plt.title(r'Simple Linear Regression')
        +plt.show()
         

        -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. -

        +This example serves several aims. It allows us to demonstrate several +aspects of data analysis and later machine learning algorithms. The +immediate visualization shows that our linear fit is not +impressive. It goes through the data points, but there are many +outliers which are not reproduced by our linear regression. We could +now play around with this small program and change for example the +factor in front of \( x \) and the normal distribution. Try to change the +function \( y \) to +

         
        +$$ +y = 10x+0.01N(0,1), +$$ +

         
        -

        -

        Introduction to Jupyter notebook and available tools

        +

        +where \( x \) is defined as before. Does the fit look better? Indeed, by +reducing the role of the normal distribution we see immediately that +our linear prediction seemingly reproduces better the training +set. However, this testing 'by the eye' is obviouly not satisfactory in the +long run. Here we have only defined the training data and our model, and +have not discussed a more rigorous approach to the cost function. + +

        +We need more rigorous criteria in defining whether we have succeed or +not in modeling our training data. You will be surprised to see that +many scientists seldomly venture beyond this 'by the eye' approach. A +standard approach for the cost function is the so-called \( \chi^2 \) +function + +

         
        +$$ \chi^2 = \frac{1}{n} +\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, +$$ +

         
        + +

        +where \( \sigma_i^2 \) is the variance (to be defined later) of the entry +\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves +however the aim of scaling the equations and make the cost function +dimensionless. + +

        +Minimizing the cost function is a central aspect of +our discussions to come. Finding its minima as function of the model +parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring +theme in these series of lectures. Essentially all machine learning +algorithms we will discuss center around the minimization of the +chosen cost function. This depends in turn on our specific +model for describing the data, a typical situation in supervised +learning. Automatizing the search for the minima of the cost function is a +central ingredient in all algorithms. Typical methods which are +employed are various variants of gradient methods. These will be +discussed in more detail later. Again, you'll be surprised to hear that +many practitioners minimize the above function ''by the eye', popularly dubbed as +'chi by the eye'. That is, change a parameter and see (visually and numerically) that +the your \( \chi^2 \) function becomes smaller. + +

        +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 +the relative error as +

         
        +$$ +\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. +$$ +

         
        + +We can modify easily the above Python code and plot the relative instead +

        + + +

        import numpy as np
        +import matplotlib.pyplot as plt
        +from sklearn.linear_model import LinearRegression
        +
        +x = np.random.rand(100,1)
        +y = 5*x+0.01*np.random.randn(100,1)
        +linreg = LinearRegression()
        +linreg.fit(x,y)
        +ypredict = linreg.predict(x)
        +
        +plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
        +plt.axis([0,1.0,0.0, 0.5])
        +plt.xlabel(r'$x$')
        +plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
        +plt.title(r'Relative error')
        +plt.show()
        +
        +

        +Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. + +

        +As mentioned above, scikit-learn has an impressive functionality. +We can for example extract the values of \( \alpha \) and \( \beta \) and their error estimates, +or the variance and standard deviation and many other properties from the statistical data analysis. Here we show an example of the functionality of scikit-learn. +

        + + +

        import numpy as np
        +import matplotlib.pyplot as plt
        +from sklearn.linear_model import LinearRegression
        +from sklearn.metrics import mean_squared_error, r2_score
        +
        +x = np.random.rand(100,1)
        +y = 2*x+np.random.randn(100,1)
        +linreg = LinearRegression()
        +linreg.fit(x,y)
        +ypredict = linreg.predict(x)
        +print('Coefficients: \n', linreg.coef_)
        +# The mean squared error                               
        +print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
        +# Explained variance score: 1 is perfect prediction                                 
        +print('Variance score: %.2f' % r2_score(y, ypredict))
        +plt.plot(x, ypredict, "r-")
        +plt.plot(x, y ,'ro')
        +plt.axis([0,1.0,0, 5.0])
        +plt.xlabel(r'$x$')
        +plt.ylabel(r'$y$')
        +plt.title(r'Linear Regression fit ')
        +plt.show()
        +
        +

        +We will come to the definition of these outputs later. + +

        +Another useful Python package is +pandas, which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. The following simple example shows an example on 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.

        @@ -308,178 +538,7 @@ display(data_pandas)
        -

        Representing data, more examples

        -
        - -

        - - -

        import numpy as np
        -import matplotlib.pyplot as plt
        -from scipy import sparse
        -import pandas as pd
        -from IPython.display import display
        -import mglearn
        -import sklearn
        -from sklearn.linear_model import LinearRegression
        -from sklearn.tree import DecisionTreeRegressor
        -x, y = mglearn.datasets.make_wave(n_samples=100)
        -line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1)
        -reg = DecisionTreeRegressor(min_samples_split=3).fit(x,y)
        -plt.plot(line, reg.predict(line), label="decision tree")
        -regline = LinearRegression().fit(x,y)
        -plt.plot(line, regline.predict(line), label= "Linear Regression")
        -plt.show()
        -
        - -
        -
        - - -
        -

        Simple regression model

        -Add info about the equations -

        - - -

        # Importing various packages
        -from random import random, seed
        -import numpy as np
        -import matplotlib.pyplot as plt
        -
        -x = 2*np.random.rand(100,1)
        -y = 4+3*x+np.random.randn(100,1)
        -
        -xb = np.c_[np.ones((100,1)), x]
        -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
        -xnew = np.array([[0],[2]])
        -xbnew = np.c_[np.ones((2,1)), xnew]
        -ypredict = xbnew.dot(theta)
        -
        -plt.plot(xnew, ypredict, "r-")
        -plt.plot(x, y ,'ro')
        -plt.axis([0,2.0,0, 15.0])
        -plt.xlabel(r'$x$')
        -plt.ylabel(r'$y$')
        -plt.title(r'Linear Regression')
        -plt.show()
        -
        -
        - - -
        -

        Simple regression model, now using scikit-learn

        -Add info about the equations -

        - - -

        # Importing various packages
        -from random import random, seed
        -import numpy as np
        -import matplotlib.pyplot as plt
        -from sklearn.linear_model import LinearRegression
        -
        -x = 2*np.random.rand(100,1)
        -y = 4+3*x+np.random.randn(100,1)
        -linreg = LinearRegression()
        -linreg.fit(x,y)
        -xnew = np.array([[0],[2]])
        -ypredict = linreg.predict(xnew)
        -
        -plt.plot(xnew, ypredict, "r-")
        -plt.plot(x, y ,'ro')
        -plt.axis([0,2.0,0, 15.0])
        -plt.xlabel(r'$x$')
        -plt.ylabel(r'$y$')
        -plt.title(r'Random numbers ')
        -plt.show()
        -
        -
        - - -
        -

        Simple regression model with gradient descent

        -Add info about the equations, play around with different learning rates -

        - - -

        # Importing various packages
        -from math import exp, sqrt
        -from random import random, seed
        -import numpy as np
        -import matplotlib.pyplot as plt
        -
        -x = 2*np.random.rand(100,1)
        -y = 4+3*x+np.random.randn(100,1)
        -
        -xb = np.c_[np.ones((100,1)), x]
        -theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
        -print(theta_linreg)
        -theta = np.random.randn(2,1)
        -
        -eta = 0.1
        -Niterations = 1000
        -m = 100
        -
        -for iter in range(Niterations):
        -    gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)
        -    theta -= eta*gradients
        -
        -print(theta)
        -xnew = np.array([[0],[2]])
        -xbnew = np.c_[np.ones((2,1)), xnew]
        -ypredict = xbnew.dot(theta)
        -ypredict2 = xbnew.dot(theta_linreg)
        -plt.plot(xnew, ypredict, "r-")
        -plt.plot(xnew, ypredict2, "b-")
        -plt.plot(x, y ,'ro')
        -plt.axis([0,2.0,0, 15.0])
        -plt.xlabel(r'$x$')
        -plt.ylabel(r'$y$')
        -plt.title(r'Random numbers ')
        -plt.show()
        -
        -
        - - -
        -

        Simple regression model with stochastic gradient descent

        -Add info about the equations, play around with different learning rates -

        - - -

        # Importing various packages
        -from math import exp, sqrt
        -from random import random, seed
        -import numpy as np
        -import matplotlib.pyplot as plt
        -from sklearn.linear_model import SGDRegressor
        -
        -x = 2*np.random.rand(100,1)
        -y = 4+3*x+np.random.randn(100,1)
        -
        -xb = np.c_[np.ones((100,1)), x]
        -theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
        -print(theta_linreg)
        -sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
        -sgdreg.fit(x,y.ravel())
        -print(sgdreg.intercept_, sgdreg.coef_)
        -
        -
        - - -
        -

        Polynomial regression

        -

        - - -

        
        -
        -
        - - -
        -

        Predator-Prey model from ecology

        +

        Predator-Prey model from ecology

        @@ -502,7 +561,7 @@ scientific method:
        -

        Case study from Hudson bay

        +

        Case study from Hudson bay

        @@ -522,7 +581,7 @@ Here we start by
        -

        Hudson bay data

        +

        Hudson bay data

        @@ -568,7 +627,7 @@ One reason that this particular system has been so extensively studied is that t
        -

        Plotting the data

        +

        Plotting the data

        @@ -602,7 +661,7 @@ plt.show()
        -

        Hares and lynx in Hudson bay from 1900 to 1920

        +

        Hares and lynx in Hudson bay from 1900 to 1920





        @@ -610,7 +669,7 @@ plt.show()
        -

        Why now create a computer model for the hare and lynx populations?

        +

        Why now create a computer model for the hare and lynx populations?

        @@ -642,7 +701,7 @@ climate and other complicating factors. How significant are these?

        -

        The traditional (top-down) approach

        +

        The traditional (top-down) approach

        @@ -677,7 +736,7 @@ ODEs (which cannot be solved)
        -

        Basic mathematics notation

        +

        Basic mathematics notation