Added more scikit-learn functions

This commit is contained in:
mhjensen
2018-05-27 23:19:29 -04:00
parent 17afb32e08
commit b4246a0ebd
10 changed files with 581 additions and 303 deletions
+101 -61
View File
@@ -156,7 +156,7 @@ MathJax.Hub.Config({
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
<br>
<p>
<center><h4>May 26, 2018</h4></center> <!-- date -->
<center><h4>May 27, 2018</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -166,27 +166,27 @@ MathJax.Hub.Config({
<p>
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.
different algorithms used in the fields of data analysis and machine learning.
<p>
However, where possible we will emphasize the
importance of using available software. We start thus with a hands-on
and top-down approach to machine learning. The aim is thus to start with
relevant data and use these to introduce statistical data analysis
relevant data or data we have produced
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 in the beginning, start with simple
polynomials with random noise added, and using the Python
software package <a href="http://scikit-learn.org/stable/" target="_blank">Scikit-learn</a> we
will introduce various machine learning algorithms to make fits of
polynomials with random noise added. We will use the Python
software package <a href="http://scikit-learn.org/stable/" target="_blank">Scikit-learn</a> and
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 included in for example
<b>scikit-learn</b>. 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.
<b>scikit-learn</b>.
<p>
All these examples will serve us the purpose of getting us started, furthermore, they
These examples will serve us the purpose of getting 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
@@ -204,7 +204,7 @@ Moreover, the examples we introduce will serve as inputs to many of our discussi
<p>
We will make extensive use of Python as programming language and its
myriad of available libraries. Furthermore, you will find
myriad of available libraries. You will find
IPython/Jupyter notebooks invaluable in your work. You can run <b>R</b>
codes in the Jupyter/IPython notebooks, with the immediate benefit of
visualizing your data. You can also use compiled languages like C++,
@@ -216,16 +216,23 @@ a Jupyter notebook.
<p>
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 <b>pip</b> as o pip install
numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas
pillow For Python3, replace <b>pip</b> with <b>pip3</b>.
you install the following Python packages via <b>pip</b> as
<ol>
<li> pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow</li>
</ol>
For Python3, replace <b>pip</b> with <b>pip3</b>.
<p>
For OSX users we recommend also, after having installed Xcode, to
For OSX users we recommend, after having installed Xcode, to
install <b>brew</b>. Brew allows for a seamless installation of additional
software via for example o brew install python3
software via for example
<ol>
<li> brew install python3</li>
</ol>
<p>
For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
you can use <b>pip</b> as well and simply install Python as
@@ -244,13 +251,23 @@ etc etc.
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
<a href="https://docs.anaconda.com/" target="_blank">Anaconda</a>, which is an open source
dependencies for Python, namely
<ol>
<li> <a href="https://docs.anaconda.com/" target="_blank">Anaconda</a>,</li>
</ol>
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 <b>conda</b> o <a href="https://www.enthought.com/product/canopy/" target="_blank">Enthought
canopy</a> is a Python
are managed by the package management system <b>conda</b>.
<ol>
<li> <a href="https://www.enthought.com/product/canopy/" target="_blank">Enthought canopy</a></li>
</ol>
is a Python
distribution for scientific and analytic computing distribution and
analysis environment, available for free and under a commercial
license.
@@ -273,8 +290,8 @@ and allows for an easy usage of the tools we will discuss in these
texts.
<p>
To install <b>R</b> with Jupyter notebook <a href="https://mpacer.org/maths/r-kernel-for-ipython-notebook" target="_blank">following the link
here</a>
To install <b>R</b> with Jupyter notebook
<a href="https://mpacer.org/maths/r-kernel-for-ipython-notebook" target="_blank">follow the link here</a>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
@@ -298,23 +315,27 @@ 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 <b>PDF</b> file or a Latex file for
further processing. For example, convert to latex as
further processing. For example, convert to latex as
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>pycod jupyter nbconvert filename.ipynb --to latex
</pre></div>
<p>
And to add more versatility, symbolic Python package <a href="http://www.sympy.org/en/index.html" target="_blank">SymPy</a> is Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.
And to add more versatility, the Python package <a href="http://www.sympy.org/en/index.html" target="_blank">SymPy</a> is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.
<p>
Finally, if you wish to use the light mark-up language <a href="https://github.com/hplgit/doconce" target="_blank">doconce</a> you can convert a standard ascii text file into various HTML
Finally, if you wish to use the light mark-up language
<a href="https://github.com/hplgit/doconce" target="_blank">doconce</a> you can convert a standard ascii text file into various HTML
formats, ipython notebooks, latex files, pdf files etc with minimal edits.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec5">Simple linear regression model using <b>scikit-learn</b> </h2>
<p>
We start with perhaps our simplest possible example, using <b>scikit-learn</b> 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.
@@ -353,7 +374,7 @@ prediction <b>ypredict</b> (\( \tilde{y} \)), which attempts at fitting our
data with a straight line.
<p>
The Python follows here.
The Python code follows here.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
@@ -430,11 +451,12 @@ employed are various variants of <b>gradient</b> 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.
the \( \chi^2 \) function becomes smaller.
<p>
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}.
$$
@@ -461,75 +483,93 @@ plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
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.
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.
<p>
As mentioned above, <b>scikit-learn</b> 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.
As mentioned above, <b>scikit-learn</b> 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.
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error, r2_score
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+</span> <span style="color: #666666">5*</span>x<span style="color: #666666">+0.5</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
linreg <span style="color: #666666">=</span> LinearRegression()
linreg<span style="color: #666666">.</span>fit(x,y)
ypredict <span style="color: #666666">=</span> linreg<span style="color: #666666">.</span>predict(x)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Coefficients: </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, linreg<span style="color: #666666">.</span>coef_)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;The intercept alpha: </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, linreg<span style="color: #666666">.</span>intercept_)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Coefficient beta : </span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">&#39;</span>, linreg<span style="color: #666666">.</span>coef_)
<span style="color: #408080; font-style: italic"># The mean squared error </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Mean squared error: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&quot;</span> <span style="color: #666666">%</span> mean_squared_error(y, ypredict))
<span style="color: #408080; font-style: italic"># Explained variance score: 1 is perfect prediction </span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Variance score: </span><span style="color: #BB6688; font-weight: bold">%.2f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> r2_score(y, ypredict))
plt<span style="color: #666666">.</span>plot(x, ypredict, <span style="color: #BA2121">&quot;r-&quot;</span>)
plt<span style="color: #666666">.</span>plot(x, y ,<span style="color: #BA2121">&#39;ro&#39;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">0</span>, <span style="color: #666666">5.0</span>])
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0.0</span>,<span style="color: #666666">1.0</span>,<span style="color: #666666">1.5</span>, <span style="color: #666666">7.0</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&#39;$x$&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&#39;$y$&#39;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&#39;Linear Regression fit &#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
We will come to the definition of these outputs later.
The function <b>coef</b> gives us the parameter \( \beta \) of our fit while <b>intercept</b> yields
\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function <b>meansquarederror</b> gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as
$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
$$
<p>
The smaller the value, the better the fit. Ideally we would like to
have an MSE equal zero. The attentive reader has probably recognized
this function as being similar to the \( \chi^2 \) function defined above.
<p>
The <b>r2score</b> function computes \( R^2 \), the coefficient of
determination. It provides a measure of how well future samples are
likely to be predicted by the model. Best possible score is 1.0 and it
can be negative (because the model can be arbitrarily worse). A
constant model that always predicts the expected value of \( \hat{y} \),
disregarding the input features, would get a \( R^2 \) score of \( 0.0 \).
<p>
If \( \tilde{\hat{y}}_i \) is the predicted value of the i-th sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
$$
R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
$$
where the mean value
$$
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
$$
We will discuss in more detail these and more function in the various lectures.
<p>
Another useful Python package is
<a href="https://pandas.pydata.org/" target="_blank">pandas</a>, 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 <b>pandas</b>, in particular in connection with classification of data.
analysis tools for Python. The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, city of residence and age, and displays the data in an easy to read way. We will see repeated use of <b>pandas</b>, in particular in connection with classification of data.
<p>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">scipy</span> <span style="color: #008000; font-weight: bold">import</span> sparse
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
eye <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(<span style="color: #666666">4</span>)
<span style="color: #008000; font-weight: bold">print</span>(eye)
sparse_mtx <span style="color: #666666">=</span> sparse<span style="color: #666666">.</span>csr_matrix(eye)
<span style="color: #008000; font-weight: bold">print</span>(sparse_mtx)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-10</span>,<span style="color: #666666">10</span>,<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sin(x)
plt<span style="color: #666666">.</span>plot(x,y,marker<span style="color: #666666">=</span><span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>show()
data <span style="color: #666666">=</span> {<span style="color: #BA2121">&#39;Name&#39;</span>: [<span style="color: #BA2121">&quot;John&quot;</span>, <span style="color: #BA2121">&quot;Anna&quot;</span>, <span style="color: #BA2121">&quot;Peter&quot;</span>, <span style="color: #BA2121">&quot;Linda&quot;</span>], <span style="color: #BA2121">&#39;Location&#39;</span>: [<span style="color: #BA2121">&quot;Nairobi&quot;</span>, <span style="color: #BA2121">&quot;Napoli&quot;</span>, <span style="color: #BA2121">&quot;London&quot;</span>, <span style="color: #BA2121">&quot;Buenos Aires&quot;</span>], <span style="color: #BA2121">&#39;Age&#39;</span>:[<span style="color: #666666">51</span>, <span style="color: #666666">21</span>, <span style="color: #666666">34</span>, <span style="color: #666666">45</span>]}
data_pandas <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(data)
display(data_pandas)
</pre></div>
</div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>