diff --git a/doc/pub/How2ReadData/html/How2ReadData-bs.html b/doc/pub/How2ReadData/html/How2ReadData-bs.html index fc1b28984..1ba3bccfe 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-bs.html +++ b/doc/pub/How2ReadData/html/How2ReadData-bs.html @@ -191,7 +191,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

May 26, 2018

+

May 27, 2018


@@ -204,27 +204,27 @@ MathJax.Hub.Config({

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

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 Scikit-learn we -will introduce various machine learning algorithms to make fits of +polynomials with random noise added. We will use the Python +software package Scikit-learn 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 -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. +scikit-learn.

-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 @@ -242,7 +242,7 @@ Moreover, the examples we introduce will serve as inputs to many of our discussi

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 R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, @@ -254,16 +254,23 @@ 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. +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.

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

    +
  1. brew install python3
  2. +
-

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 @@ -282,13 +289,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 -Anaconda, which is an open source +dependencies for Python, namely + +

    +
  1. Anaconda,
  2. +
+ +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 +are managed by the package management system conda. + +
    +
  1. Enthought canopy
  2. +
+ +is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. @@ -311,8 +328,8 @@ 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 +follow the link here

@@ -336,23 +353,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 PDF file or a Latex file for -further processing. For example, convert to latex as +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. +And to add more versatility, the Python package SymPy is a 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 +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. @@ -391,7 +412,7 @@ prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line.

-The Python follows here. +The Python code follows here.

@@ -468,11 +489,12 @@ 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. +the \( \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}. $$ @@ -499,76 +521,93 @@ plt.title(r' 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. +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. +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
+
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)
+y = 2.0+ 5*x+0.5np.random.randn(100,1)
 linreg = LinearRegression()
 linreg.fit(x,y)
 ypredict = linreg.predict(x)
-print('Coefficients: \n', linreg.coef_)
+print('The intercept alpha: \n', linreg.intercept_)
+print('Coefficient beta : \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.axis([0.0,1.0,1.5, 7.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. +The function coef gives us the parameter \( \beta \) of our fit while intercept 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 meansquarederror 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, +$$ + +

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

+The r2score 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 \). + +

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

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. +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 pandas, in particular in connection with classification of data. -

-

-
-

-

import numpy as np
-import matplotlib.pyplot as plt
-from scipy import sparse
-import pandas as pd
+
import pandas as pd
 from IPython.display import display
-eye = np.eye(4)
-print(eye)
-sparse_mtx = sparse.csr_matrix(eye)
-print(sparse_mtx)
-x = np.linspace(-10,10,100)
-y = np.sin(x)
-plt.plot(x,y,marker='x')
-plt.show()
 data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
 data_pandas = pd.DataFrame(data)
 display(data_pandas)
 
-

-

-
- -

diff --git a/doc/pub/How2ReadData/html/How2ReadData-reveal.html b/doc/pub/How2ReadData/html/How2ReadData-reveal.html index 370fc5239..65e6a837d 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 26, 2018

+

May 27, 2018


@@ -164,27 +164,27 @@ MathJax.Hub.Config({

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

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 Scikit-learn we -will introduce various machine learning algorithms to make fits of +polynomials with random noise added. We will use the Python +software package Scikit-learn 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 -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. +scikit-learn.

-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 @@ -202,7 +202,7 @@ Moreover, the examples we introduce will serve as inputs to many of our discussi

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 R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, @@ -214,16 +214,25 @@ 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. +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.

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

    +

  1. brew install python3
  2. +

+ 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 @@ -243,13 +252,25 @@ 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 -Anaconda, which is an open source +dependencies for Python, namely + +

    +

  1. Anaconda,
  2. +
+

+ +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 +are managed by the package management system conda. + +

    +

  1. Enthought canopy
  2. +
+

+ +is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. @@ -272,8 +293,8 @@ 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 +follow the link here @@ -297,23 +318,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 PDF file or a Latex file for -further processing. For example, convert to latex as +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. +And to add more versatility, the Python package SymPy is a 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 +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. @@ -354,7 +379,7 @@ prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line.

-The Python follows here. +The Python code follows here.

@@ -435,11 +460,12 @@ 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. +the \( \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}. @@ -468,72 +494,100 @@ 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. +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. +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
+
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)
+y = 2.0+ 5*x+0.5np.random.randn(100,1)
 linreg = LinearRegression()
 linreg.fit(x,y)
 ypredict = linreg.predict(x)
-print('Coefficients: \n', linreg.coef_)
+print('The intercept alpha: \n', linreg.intercept_)
+print('Coefficient beta : \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.axis([0.0,1.0,1.5, 7.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. +The function coef gives us the parameter \( \beta \) of our fit while intercept 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 meansquarederror 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, +$$ +

 
+ +

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

+The r2score 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 \). + +

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

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. +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 pandas, in particular in connection with classification of data. -

-

-

-

import numpy as np
-import matplotlib.pyplot as plt
-from scipy import sparse
-import pandas as pd
+
import pandas as pd
 from IPython.display import display
-eye = np.eye(4)
-print(eye)
-sparse_mtx = sparse.csr_matrix(eye)
-print(sparse_mtx)
-x = np.linspace(-10,10,100)
-y = np.sin(x)
-plt.plot(x,y,marker='x')
-plt.show()
 data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
 data_pandas = pd.DataFrame(data)
 display(data_pandas)
 
- -
diff --git a/doc/pub/How2ReadData/html/How2ReadData-solarized.html b/doc/pub/How2ReadData/html/How2ReadData-solarized.html index b45e34517..d94d3ec23 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-solarized.html +++ b/doc/pub/How2ReadData/html/How2ReadData-solarized.html @@ -151,7 +151,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

May 26, 2018

+

May 27, 2018












@@ -161,27 +161,27 @@ MathJax.Hub.Config({

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

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 Scikit-learn we -will introduce various machine learning algorithms to make fits of +polynomials with random noise added. We will use the Python +software package Scikit-learn 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 -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. +scikit-learn.

-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 @@ -199,7 +199,7 @@ Moreover, the examples we introduce will serve as inputs to many of our discussi

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 R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, @@ -211,16 +211,23 @@ 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. +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.

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

    +
  1. brew install python3
  2. +
-

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 @@ -239,13 +246,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 -Anaconda, which is an open source +dependencies for Python, namely + +

    +
  1. Anaconda,
  2. +
+ +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 +are managed by the package management system conda. + +
    +
  1. Enthought canopy
  2. +
+ +is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. @@ -268,8 +285,8 @@ 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 +follow the link here











@@ -293,23 +310,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 PDF file or a Latex file for -further processing. For example, convert to latex as +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. +And to add more versatility, the Python package SymPy is a 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 +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. @@ -348,7 +369,7 @@ prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line.

-The Python follows here. +The Python code follows here.

@@ -425,11 +446,12 @@ 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. +the \( \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}. $$ @@ -456,75 +478,93 @@ 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. +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. +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
+
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)
+y = 2.0+ 5*x+0.5np.random.randn(100,1)
 linreg = LinearRegression()
 linreg.fit(x,y)
 ypredict = linreg.predict(x)
-print('Coefficients: \n', linreg.coef_)
+print('The intercept alpha: \n', linreg.intercept_)
+print('Coefficient beta : \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.axis([0.0,1.0,1.5, 7.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. +The function coef gives us the parameter \( \beta \) of our fit while intercept 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 meansquarederror 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, +$$ + +

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

+The r2score 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 \). + +

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

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. +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 pandas, in particular in connection with classification of data. -

-

- -

-

import numpy as np
-import matplotlib.pyplot as plt
-from scipy import sparse
-import pandas as pd
+
import pandas as pd
 from IPython.display import display
-eye = np.eye(4)
-print(eye)
-sparse_mtx = sparse.csr_matrix(eye)
-print(sparse_mtx)
-x = np.linspace(-10,10,100)
-y = np.sin(x)
-plt.plot(x,y,marker='x')
-plt.show()
 data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
 data_pandas = pd.DataFrame(data)
 display(data_pandas)
 
- -
- -











diff --git a/doc/pub/How2ReadData/html/How2ReadData.html b/doc/pub/How2ReadData/html/How2ReadData.html index 5720176ae..86a01beb0 100644 --- a/doc/pub/How2ReadData/html/How2ReadData.html +++ b/doc/pub/How2ReadData/html/How2ReadData.html @@ -156,7 +156,7 @@ MathJax.Hub.Config({

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

-

May 26, 2018

+

May 27, 2018












@@ -166,27 +166,27 @@ MathJax.Hub.Config({

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

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 Scikit-learn we -will introduce various machine learning algorithms to make fits of +polynomials with random noise added. We will use the Python +software package Scikit-learn 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 -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. +scikit-learn.

-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

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

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

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

    +
  1. brew install python3
  2. +
-

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 @@ -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 -Anaconda, which is an open source +dependencies for Python, namely + +

    +
  1. Anaconda,
  2. +
+ +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 +are managed by the package management system conda. + +
    +
  1. Enthought canopy
  2. +
+ +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.

-To install R with Jupyter notebook following the link -here +To install R with Jupyter notebook +follow the link here











@@ -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 PDF file or a Latex file for -further processing. For example, convert to latex as +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. +And to add more versatility, the Python package SymPy is a 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 +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. @@ -353,7 +374,7 @@ prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line.

-The Python follows here. +The Python code follows here.

@@ -430,11 +451,12 @@ 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. +the \( \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}. $$ @@ -461,75 +483,93 @@ plt.title(r' 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. +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. +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
+
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)
+y = 2.0+ 5*x+0.5np.random.randn(100,1)
 linreg = LinearRegression()
 linreg.fit(x,y)
 ypredict = linreg.predict(x)
-print('Coefficients: \n', linreg.coef_)
+print('The intercept alpha: \n', linreg.intercept_)
+print('Coefficient beta : \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.axis([0.0,1.0,1.5, 7.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. +The function coef gives us the parameter \( \beta \) of our fit while intercept 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 meansquarederror 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, +$$ + +

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

+The r2score 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 \). + +

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

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. +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 pandas, in particular in connection with classification of data. -

-

- -

-

import numpy as np
-import matplotlib.pyplot as plt
-from scipy import sparse
-import pandas as pd
+
import pandas as pd
 from IPython.display import display
-eye = np.eye(4)
-print(eye)
-sparse_mtx = sparse.csr_matrix(eye)
-print(sparse_mtx)
-x = np.linspace(-10,10,100)
-y = np.sin(x)
-plt.plot(x,y,marker='x')
-plt.show()
 data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
 data_pandas = pd.DataFrame(data)
 display(data_pandas)
 
- -
- -











diff --git a/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb b/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb index 6d845b8af..2740fa422 100644 --- a/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb +++ b/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **May 26, 2018**\n", + "Date: **May 27, 2018**\n", "\n", "Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -24,25 +24,24 @@ "Our emphasis throughout this series of lectures \n", "is on understanding the mathematical aspects of\n", "different algorithms used in the fields of data analysis and machine learning. \n", + "\n", "However, where possible we will emphasize the\n", "importance of using available software. We start thus with a hands-on\n", "and top-down approach to machine learning. The aim is thus to start with\n", - "relevant data and use these to introduce statistical data analysis\n", + "relevant data or data we have produced \n", + "and use these to introduce statistical data analysis\n", "concepts and machine learning algorithms before we delve into the\n", "algorithms themselves. The examples we will use in the beginning, start with simple\n", - "polynomials with random noise added, and using the Python\n", - "software package [Scikit-learn](http://scikit-learn.org/stable/) we\n", - "will introduce various machine learning algorithms to make fits of\n", + "polynomials with random noise added. We will use the Python\n", + "software package [Scikit-learn](http://scikit-learn.org/stable/) and\n", + "introduce various machine learning algorithms to make fits of\n", "the data and predictions. We move thereafter to more interesting\n", "cases such as the simulation of financial transactions or disease\n", "models. These are examples where we can easily set up the data and\n", "then use machine learning algorithms included in for example\n", - "**scikit-learn**. Another model we will consider is the so-called Ising\n", - "model. Here we will use this model to produce data for selected spin\n", - "configurations and attempt to classify the data. Finally, our last\n", - "example consists of economic data from the OECD. \n", + "**scikit-learn**. \n", "\n", - "All these examples will serve us the purpose of getting us started, furthermore, they\n", + "These examples will serve us the purpose of getting started. Furthermore, they\n", "allow us to catch more than two birds with a stone. They will allow us\n", "to bring in some programming specific topics and tools as well as\n", "showing the power of various Python (and R) packages for machine\n", @@ -59,7 +58,7 @@ "## Software and needed installations\n", "\n", "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. Furthermore, you will find\n", + "myriad of available libraries. You will find\n", "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", "visualizing your data. You can also use compiled languages like C++,\n", @@ -71,16 +70,21 @@ "\n", "If you have Python installed (we recommend Python3) and you feel\n", "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as o pip install\n", - "numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas\n", - "pillow For Python3, replace **pip** with **pip3**.\n", + "you install the following Python packages via **pip** as \n", "\n", - "For OSX users we recommend also, after having installed Xcode, to\n", + "1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n", + "\n", + "For Python3, replace **pip** with **pip3**.\n", + "\n", + "For OSX users we recommend, after having installed Xcode, to\n", "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example o brew install python3\n", + "software via for example \n", + "\n", + "1. brew install python3\n", "\n", "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", "you can use **pip** as well and simply install Python as \n", + "\n", "1. sudo apt-get install python3 (or python for pyhton2.7)\n", "\n", "etc etc. \n", @@ -90,13 +94,19 @@ "If you don't want to perform these operations separately and venture\n", "into the hassle of exploring how to set up dependencies and paths, we\n", "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely o\n", - "[Anaconda](https://docs.anaconda.com/), which is an open source\n", + "dependencies for Python, namely \n", + "\n", + "1. [Anaconda](https://docs.anaconda.com/), \n", + "\n", + "which is an open source\n", "distribution of the Python and R programming languages for large-scale\n", "data processing, predictive analytics, and scientific computing, that\n", "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda** o [Enthought\n", - "canopy](https://www.enthought.com/product/canopy/) is a Python\n", + "are managed by the package management system **conda**. \n", + "\n", + "1. [Enthought canopy](https://www.enthought.com/product/canopy/) \n", + "\n", + "is a Python\n", "distribution for scientific and analytic computing distribution and\n", "analysis environment, available for free and under a commercial\n", "license.\n", @@ -115,8 +125,8 @@ "and allows for an easy usage of the tools we will discuss in these\n", "texts.\n", "\n", - "To install **R** with Jupyter notebook [following the link\n", - "here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", + "To install **R** with Jupyter notebook \n", + "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", "\n", "\n", "\n", @@ -152,12 +162,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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. \n", + "And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n", "\n", - "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 \n", + "Finally, if you wish to use the light mark-up language \n", + "[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n", "formats, ipython notebooks, latex files, pdf files etc with minimal edits.\n", "\n", "## Simple linear regression model using **scikit-learn**\n", + "\n", "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", "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.\n", "\n", @@ -203,7 +215,7 @@ "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", "data with a straight line.\n", "\n", - "The Python follows here." + "The Python code follows here." ] }, { @@ -310,7 +322,7 @@ "discussed in more detail later. Again, you'll be surprised to hear that\n", "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", - "the your $\\chi^2$ function becomes smaller. \n", + "the $\\chi^2$ function becomes smaller. \n", "\n", "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 \n", "the relative error as" @@ -362,11 +374,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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. \n", + "Depending on the parameter in front of the normal distribution, we may\n", + "have a small or larger relative error. Try to play around with\n", + "different training data sets and study (graphically) the value of the\n", + "relative error.\n", "\n", - "As mentioned above, **scikit-learn** has an impressive functionality. \n", - "We can for example extract the values of $\\alpha$ and $\\beta$ and their error estimates,\n", - "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, **scikit-learn** has an impressive functionality.\n", + "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", + "their error estimates, or the variance and standard deviation and many\n", + "other properties from the statistical data analysis. Here we show an\n", + "example of the functionality of scikit-learn." ] }, { @@ -377,24 +394,25 @@ }, "outputs": [], "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", + "import numpy as np \n", + "import matplotlib.pyplot as plt \n", + "from sklearn.linear_model import LinearRegression \n", "from sklearn.metrics import mean_squared_error, r2_score\n", "\n", "x = np.random.rand(100,1)\n", - "y = 2*x+np.random.randn(100,1)\n", + "y = 2.0+ 5*x+0.5np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "ypredict = linreg.predict(x)\n", - "print('Coefficients: \\n', linreg.coef_)\n", + "print('The intercept alpha: \\n', linreg.intercept_)\n", + "print('Coefficient beta : \\n', linreg.coef_)\n", "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(y, ypredict))\n", "plt.plot(x, ypredict, \"r-\")\n", "plt.plot(x, y ,'ro')\n", - "plt.axis([0,1.0,0, 5.0])\n", + "plt.axis([0.0,1.0,1.5, 7.0])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$y$')\n", "plt.title(r'Linear Regression fit ')\n", @@ -405,12 +423,73 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We will come to the definition of these outputs later. \n", + "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", + "$\\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 **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The smaller the value, the better the fit. Ideally we would like to\n", + "have an MSE equal zero. The attentive reader has probably recognized\n", + "this function as being similar to the $\\chi^2$ function defined above.\n", + "\n", + "The **r2score** function computes $R^2$, the coefficient of\n", + "determination. It provides a measure of how well future samples are\n", + "likely to be predicted by the model. Best possible score is 1.0 and it\n", + "can be negative (because the model can be arbitrarily worse). A\n", + "constant model that always predicts the expected value of $\\hat{y}$,\n", + "disregarding the input features, would get a $R^2$ score of $0.0$.\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "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},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the mean value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will discuss in more detail these and more function in the various lectures.\n", "\n", "Another useful Python package is\n", "[pandas](https://pandas.pydata.org/), which is an open source library\n", "providing high-performance, easy-to-use data structures and data\n", - "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." + "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 **pandas**, in particular in connection with classification of data." ] }, { @@ -421,19 +500,8 @@ }, "outputs": [], "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from scipy import sparse\n", "import pandas as pd\n", "from IPython.display import display\n", - "eye = np.eye(4)\n", - "print(eye)\n", - "sparse_mtx = sparse.csr_matrix(eye)\n", - "print(sparse_mtx)\n", - "x = np.linspace(-10,10,100)\n", - "y = np.sin(x)\n", - "plt.plot(x,y,marker='x')\n", - "plt.show()\n", "data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Nairobi\", \"Napoli\", \"London\", \"Buenos Aires\"], 'Age':[51, 21, 34, 45]}\n", "data_pandas = pd.DataFrame(data)\n", "display(data_pandas)" diff --git a/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz b/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz index 54b6bfebb..cd3398822 100644 Binary files a/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz and b/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz differ diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf index 88c90fe3d..ab4b8a44b 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf differ diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf index 2c56c4584..ce4ebd224 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf differ diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf index 497565171..20ba078c7 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf differ diff --git a/doc/src/How2ReadData/How2ReadData.do.txt b/doc/src/How2ReadData/How2ReadData.do.txt index dfa1895c5..ae1b6058b 100644 --- a/doc/src/How2ReadData/How2ReadData.do.txt +++ b/doc/src/How2ReadData/How2ReadData.do.txt @@ -93,7 +93,7 @@ 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 "Enthoughtmcanopy":"https://www.enthought.com/product/canopy/" +o "Enthought canopy":"https://www.enthought.com/product/canopy/" is a Python distribution for scientific and analytic computing distribution and @@ -296,37 +296,74 @@ plt.title(r'Relative error') plt.show() !ec -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. -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. -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression +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. +!bc pycod +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) +y = 2.0+ 5*x+0.5np.random.randn(100,1) linreg = LinearRegression() linreg.fit(x,y) ypredict = linreg.predict(x) -print('Coefficients: \n', linreg.coef_) +print('The intercept alpha: \n', linreg.intercept_) +print('Coefficient beta : \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.axis([0.0,1.0,1.5, 7.0]) plt.xlabel(r'$x$') plt.ylabel(r'$y$') plt.title(r'Linear Regression fit ') plt.show() !ec -We will come to the definition of these outputs later. +The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ 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 _meansquarederror_ gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et + +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. + +The _r2score_ 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$. + +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 +!bt +\[ +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}, +\] +!et +where the mean value +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +We will discuss in more detail these and more function in the various lectures. Another useful Python package is "pandas":"https://pandas.pydata.org/", which is an open source library