Added more scikit-learn functions
This commit is contained in:
@@ -10,7 +10,7 @@
|
||||
"<!-- Author: --> \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)"
|
||||
|
||||
Reference in New Issue
Block a user