update on first chapters

This commit is contained in:
mhjensen
2018-05-25 08:29:56 -04:00
parent bfc6e38523
commit 3f3955e45b
+117 -175
View File
@@ -6,29 +6,39 @@ DATE: today
!split
===== 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":"http://scikit-learn.org/stable/" 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 to get 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 next chapter on linear algebra, we will also dive 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).
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.
@@ -36,19 +46,26 @@ All these examples will serve us to get started, furthermore, they allow us to c
!split
===== Software and needed installations =====
We will make intensive 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.
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
o pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
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
o brew install python3
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
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
@@ -57,43 +74,95 @@ etc etc.
!split
===== Python installers =====
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":"https://docs.anaconda.com/", 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":"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.
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":"https://docs.anaconda.com/", 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":"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. 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.
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":"https://mpacer.org/maths/r-kernel-for-ipython-notebook"
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 =====
===== 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. 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
!bc pycod
jupyter nbconvert filename.ipynb --to latex
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":"https://numba.pydata.org/" 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
!bc
pycod jupyter nbconvert filename.ipynb --to latex
!ec
And to add more versatility, symbolic Python package "SymPy":"http://www.sympy.org/en/index.html" is Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.
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.
Finally, if you wish to use the light mark-up language "doconce":"https://github.com/hplgit/doconce" you can convert a standard ascii text file into various HTML
formats, ipython notebooks, latex files, pdf files etc with minimal edits.
!split
===== 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).
The Numpy functions are imported used the
!bc pycod
# 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 = 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()
!ec
!split
@@ -120,65 +189,10 @@ display(data_pandas)
!ec
!eblock
!split
===== Representing data, more examples =====
!bblock
!bc pycod
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()
!ec
!eblock
!split
===== Simple regression model =====
Add info about the equations
!bc pycod
# 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()
!ec
!split
===== Simple regression model, now using _scikit-learn_ =====
===== Simple linear regression model using _scikit-learn_ =====
Add info about the equations
!bc pycod
# Importing various packages
@@ -204,78 +218,6 @@ plt.show()
!ec
!split
===== Simple regression model with gradient descent =====
Add info about the equations, play around with different learning rates
!bc pycod
# 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()
!ec
!split
===== Simple regression model with stochastic gradient descent =====
Add info about the equations, play around with different learning rates
!bc pycod
# 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_)
!ec
!split
===== Polynomial regression =====
!bc pycod
!ec
!split
===== Predator-Prey model from ecology =====
@@ -704,7 +646,7 @@ Change `r` in the program and play around to make a better fit!
!split
===== Simulating financial transcations =====
===== Simulating financial transactions =====
The aim here is to simulate financial transactions among financial agents
using Monte Carlo methods. The final goal is to extract a distribution of income as function