test
@@ -10,9 +10,9 @@
|
||||
"<!-- 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: **Nov 19, 2019**\n",
|
||||
"Date: **Sep 19, 2020**\n",
|
||||
"\n",
|
||||
"Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||||
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
@@ -94,7 +94,7 @@
|
||||
"of algorithms and methods we will discuss.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"\n",
|
||||
"## Learning outcomes\n",
|
||||
"\n",
|
||||
"These sets of lectures aim at giving you an overview of central aspects of\n",
|
||||
@@ -153,6 +153,51 @@
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Machine Learning, a small (and probably biased) introduction\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Ideally, machine learning represents the science of giving computers\n",
|
||||
"the ability to learn without being explicitly programmed. The idea is\n",
|
||||
"that there exist generic algorithms which can be used to find patterns\n",
|
||||
"in a broad class of data sets without having to write code\n",
|
||||
"specifically for each problem. The algorithm will build its own logic\n",
|
||||
"based on the data. You should however always keep in mind that\n",
|
||||
"machines and algorithms are to a large extent developed by humans. The\n",
|
||||
"insights and knowledge we have about a specific system, play a central\n",
|
||||
"role when we develop a specific machine learning algorithm. \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Machine Learning, an extremely rich field\n",
|
||||
"\n",
|
||||
"Machine learning is an extremely rich field, in spite of its young\n",
|
||||
"age. The increases we have seen during the last decades in\n",
|
||||
"computational capabilities have been followed by developments of\n",
|
||||
"methods and techniques for analyzing and handling large date sets,\n",
|
||||
"relying heavily on statistics, computer science and mathematics. The\n",
|
||||
"field is rather new and developing rapidly. Popular software libraries\n",
|
||||
"written in Python for machine learning like\n",
|
||||
"[Scikit-learn](http://scikit-learn.org/stable/),\n",
|
||||
"[Tensorflow](https://www.tensorflow.org/),\n",
|
||||
"[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n",
|
||||
"freely available at their respective GitHub sites, encompass\n",
|
||||
"communities of developers in the thousands or more. And the number of\n",
|
||||
"code developers and contributors keeps increasing.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## A multidisciplinary approach\n",
|
||||
"\n",
|
||||
"Not all the\n",
|
||||
"algorithms and methods can be given a rigorous mathematical\n",
|
||||
"justification (for example decision trees and random forests), opening up thereby large rooms for experimenting and\n",
|
||||
"trial and error and thereby exciting new developments. However, a\n",
|
||||
"solid command of linear algebra, multivariate theory, probability\n",
|
||||
"theory, statistical data analysis, understanding errors and Monte\n",
|
||||
"Carlo methods are central elements in a proper understanding of many\n",
|
||||
"of the algorithms and methods we will discuss.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Types of Machine Learning\n",
|
||||
"\n",
|
||||
@@ -170,44 +215,117 @@
|
||||
"Another way to categorize machine learning tasks is to consider the\n",
|
||||
"desired output of a system. Some of the most common tasks are:\n",
|
||||
"\n",
|
||||
" * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n",
|
||||
"* Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is often supervised learning.\n",
|
||||
"\n",
|
||||
" * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n",
|
||||
"* Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n",
|
||||
"\n",
|
||||
" * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n",
|
||||
"* Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Essential elements of ML\n",
|
||||
"\n",
|
||||
"The methods we cover have three main topics in common, irrespective of\n",
|
||||
"whether we deal with supervised or unsupervised learning. The first\n",
|
||||
"ingredient is normally our data set (which can be subdivided into\n",
|
||||
"training and test data), the second item is a model which is normally\n",
|
||||
"a function of some parameters. The model reflects our knowledge of\n",
|
||||
"the system (or lack thereof). As an example, if we know that our data\n",
|
||||
"show a behavior similar to what would be predicted by a polynomial,\n",
|
||||
"fitting our data to a polynomial of some degree would then determin\n",
|
||||
"our model.\n",
|
||||
"whether we deal with supervised or unsupervised learning.\n",
|
||||
"* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n",
|
||||
"\n",
|
||||
"The last ingredient is a so-called **cost**\n",
|
||||
"function which allows us to present an estimate on how good our model\n",
|
||||
"is in reproducing the data it is supposed to train. \n",
|
||||
"* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n",
|
||||
"\n",
|
||||
"Here we will build our machine learning approach on elements of the\n",
|
||||
"statistical foundation discussed above, with elements from data\n",
|
||||
"analysis, stochastic processes etc. We will discuss the following\n",
|
||||
"machine learning algorithms\n",
|
||||
"* The last ingredient is a so-called **cost/loss** function (or error function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n",
|
||||
"\n",
|
||||
"1. Linear regression and its variants\n",
|
||||
"\n",
|
||||
"2. Decision tree algorithms, from single trees to random forests\n",
|
||||
"\n",
|
||||
"3. Bayesian statistics and regression\n",
|
||||
"\n",
|
||||
"4. Support vector machines and finally various variants of\n",
|
||||
"\n",
|
||||
"5. Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks\n",
|
||||
"\n",
|
||||
"6. Networks for unsupervised learning using for example reduced Boltzmann machines.\n",
|
||||
"## An optimization/minimization problem\n",
|
||||
"\n",
|
||||
"## Choice of programming language\n",
|
||||
"At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## A Frequentist approach to data analysis\n",
|
||||
"\n",
|
||||
"When you hear phrases like **predictions and estimations** and\n",
|
||||
"**correlations and causations**, what do you think of? May be you think\n",
|
||||
"of the difference between classifying new data points and generating\n",
|
||||
"new data points.\n",
|
||||
"Or perhaps you consider that correlations represent some kind of symmetric statements like\n",
|
||||
"if $A$ is correlated with $B$, then $B$ is correlated with\n",
|
||||
"$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\n",
|
||||
"necessarily cause $A$.\n",
|
||||
"\n",
|
||||
"These concepts are in some sense the difference between machine\n",
|
||||
"learning and statistics. In machine learning and prediction based\n",
|
||||
"tasks, we are often interested in developing algorithms that are\n",
|
||||
"capable of learning patterns from given data in an automated fashion,\n",
|
||||
"and then using these learned patterns to make predictions or\n",
|
||||
"assessments of newly given data. In many cases, our primary concern\n",
|
||||
"is the quality of the predictions or assessments, and we are less\n",
|
||||
"concerned about the underlying patterns that were learned in order\n",
|
||||
"to make these predictions.\n",
|
||||
"\n",
|
||||
"In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\n",
|
||||
"where the aim is to make predictions and find correlations. We focus\n",
|
||||
"less on for example extracting a probability distribution function (PDF). The PDF can be\n",
|
||||
"used in turn to make estimations and find causations such as given $A$\n",
|
||||
"what is the likelihood of finding $B$.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## What is a good model?\n",
|
||||
"\n",
|
||||
"In science and engineering we often end up in situations where we want to infer (or learn) a\n",
|
||||
"quantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n",
|
||||
"\n",
|
||||
"As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\n",
|
||||
"straight line, or if we wish to be more sophisticated to a more complex\n",
|
||||
"function.\n",
|
||||
"\n",
|
||||
"The reason for inferring such a model is that it\n",
|
||||
"serves many useful purposes. On the one hand, the model can reveal information\n",
|
||||
"encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\n",
|
||||
"corelations that relate interesting physics interpretations.\n",
|
||||
"\n",
|
||||
"In addition, it can simplify the representation of the given data set and help\n",
|
||||
"us in making predictions about future data samples.\n",
|
||||
"\n",
|
||||
"A first important consideration to keep in mind is that inferring the *correct* model\n",
|
||||
"for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n",
|
||||
"is that if we are not specific about what we mean by a *correct* model, there\n",
|
||||
"could easily be many different models that fit the given data set *equally well*.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## What is a good model? Can we define it?\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The central question is this: what leads us to say that a model is correct or\n",
|
||||
"optimal for a given data set? To make the model inference problem well posed, i.e.,\n",
|
||||
"to guarantee that there is a unique optimal model for the given data, we need to\n",
|
||||
"impose additional assumptions or restrictions on the class of models considered. To\n",
|
||||
"this end, we should not be looking for just any model that can describe the data.\n",
|
||||
"Instead, we should look for a **model** $M$ that is the best among a restricted class\n",
|
||||
"of models. In addition, to make the model inference problem computationally\n",
|
||||
"tractable, we need to specify how restricted the class of models needs to be. A\n",
|
||||
"common strategy is to start \n",
|
||||
"with the simplest possible class of models that is just necessary to describe the data\n",
|
||||
"or solve the problem at hand. More precisely, the model class should be rich enough\n",
|
||||
"to contain at least one model that can fit the data to a desired accuracy and yet be\n",
|
||||
"restricted enough that it is relatively simple to find the best model for the given data.\n",
|
||||
"\n",
|
||||
"Thus, the most popular strategy is to start from the\n",
|
||||
"simplest class of models and increase the complexity of the models only when the\n",
|
||||
"simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n",
|
||||
"may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n",
|
||||
"\n",
|
||||
"How to evaluate which model fits best the data is something we will come back to over and over again in these set of lectures.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Choice of Programming Language\n",
|
||||
"\n",
|
||||
"Python plays nowadays a central role in the development of machine\n",
|
||||
"learning techniques and tools for data analysis. In particular, seen\n",
|
||||
@@ -218,38 +336,12 @@
|
||||
"compiled programs written in C++, and much more made our choice of\n",
|
||||
"programming language for this series of lectures easy. However,\n",
|
||||
"since the focus here is not only on using existing Python libraries such\n",
|
||||
"as **Scikit-Learn** or **Tensorflow**, but also on developing your own\n",
|
||||
"as **Scikit-Learn**, **Tensorflow** and **Pytorch**, but also on developing your own\n",
|
||||
"algorithms and codes, we will as far as possible present many of these\n",
|
||||
"algorithms either as a Python codes or C++ or Fortran (or other languages) codes. \n",
|
||||
"\n",
|
||||
"The reason we also focus on compiled languages like C++ (or\n",
|
||||
"Fortran), is that Python is still notoriously slow when we do not\n",
|
||||
"utilize highly streamlined computational libraries like\n",
|
||||
"[Lapack](http://www.netlib.org/lapack/) or other numerical libraries\n",
|
||||
"written in compiled languages (many of these libraries are written in\n",
|
||||
"Fortran). Although a project like [Numba](https://numba.pydata.org/)\n",
|
||||
"holds great promise for speeding up the unrolling of lengthy loops, C++\n",
|
||||
"and Fortran are presently still the performance winners. Numba gives\n",
|
||||
"you potentially the power to speed up your applications with high\n",
|
||||
"performance functions written directly in Python. In particular,\n",
|
||||
"array-oriented and math-heavy Python code can achieve similar\n",
|
||||
"performance to C, C++ and Fortran. However, even with these speed-ups,\n",
|
||||
"for codes involving heavy Markov Chain Monte Carlo analyses and\n",
|
||||
"optimizations of cost functions, C++/C or Fortran codes tend to\n",
|
||||
"outperform Python codes. \n",
|
||||
"\n",
|
||||
"Presently thus, the community tends to let\n",
|
||||
"code written in C++/C or Fortran do the heavy duty numerical\n",
|
||||
"number crunching and leave the post-analysis of the data to the above\n",
|
||||
"mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen\n",
|
||||
"the changes during the last decade, the above situation may change swiftly in the not too distant future. \n",
|
||||
"\n",
|
||||
"Many of the examples we discuss in this series of lectures come with\n",
|
||||
"existing data files or provide code examples which produce the data to\n",
|
||||
"be analyzed. Most of the applications we will discuss deal with\n",
|
||||
"small data sets (less than a terabyte of information) and can easily\n",
|
||||
"be analyzed and tested on standard off the shelf laptops you find in general \n",
|
||||
"stores.\n",
|
||||
"\n",
|
||||
"## Data handling, machine learning and ethical aspects\n",
|
||||
"\n",
|
||||
@@ -355,14 +447,15 @@
|
||||
":titlesonly:\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"gettingstarted.ipynb\n",
|
||||
"regression.ipynb\n",
|
||||
"logistic.ipynb\n",
|
||||
"chapter2\n",
|
||||
"chapter3\n",
|
||||
"chapter4\n",
|
||||
"chapter5\n",
|
||||
"```\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
<!-- Author: -->
|
||||
**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
|
||||
|
||||
Date: **Nov 19, 2019**
|
||||
Date: **Sep 19, 2020**
|
||||
|
||||
Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
||||
Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
||||
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ Carlo methods are central elements in a proper understanding of many
|
||||
of algorithms and methods we will discuss.
|
||||
|
||||
|
||||
<!-- !split -->
|
||||
|
||||
## Learning outcomes
|
||||
|
||||
These sets of lectures aim at giving you an overview of central aspects of
|
||||
@@ -147,6 +147,51 @@ machine learning.
|
||||
|
||||
|
||||
|
||||
## Machine Learning, a small (and probably biased) introduction
|
||||
|
||||
|
||||
Ideally, machine learning represents the science of giving computers
|
||||
the ability to learn without being explicitly programmed. The idea is
|
||||
that there exist generic algorithms which can be used to find patterns
|
||||
in a broad class of data sets without having to write code
|
||||
specifically for each problem. The algorithm will build its own logic
|
||||
based on the data. You should however always keep in mind that
|
||||
machines and algorithms are to a large extent developed by humans. The
|
||||
insights and knowledge we have about a specific system, play a central
|
||||
role when we develop a specific machine learning algorithm.
|
||||
|
||||
|
||||
## Machine Learning, an extremely rich field
|
||||
|
||||
Machine learning is an extremely rich field, in spite of its young
|
||||
age. The increases we have seen during the last decades in
|
||||
computational capabilities have been followed by developments of
|
||||
methods and techniques for analyzing and handling large date sets,
|
||||
relying heavily on statistics, computer science and mathematics. The
|
||||
field is rather new and developing rapidly. Popular software libraries
|
||||
written in Python for machine learning like
|
||||
[Scikit-learn](http://scikit-learn.org/stable/),
|
||||
[Tensorflow](https://www.tensorflow.org/),
|
||||
[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all
|
||||
freely available at their respective GitHub sites, encompass
|
||||
communities of developers in the thousands or more. And the number of
|
||||
code developers and contributors keeps increasing.
|
||||
|
||||
|
||||
## A multidisciplinary approach
|
||||
|
||||
Not all the
|
||||
algorithms and methods can be given a rigorous mathematical
|
||||
justification (for example decision trees and random forests), opening up thereby large rooms for experimenting and
|
||||
trial and error and thereby exciting new developments. However, a
|
||||
solid command of linear algebra, multivariate theory, probability
|
||||
theory, statistical data analysis, understanding errors and Monte
|
||||
Carlo methods are central elements in a proper understanding of many
|
||||
of the algorithms and methods we will discuss.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Types of Machine Learning
|
||||
|
||||
@@ -164,44 +209,117 @@ solely from rewards and punishment.
|
||||
Another way to categorize machine learning tasks is to consider the
|
||||
desired output of a system. Some of the most common tasks are:
|
||||
|
||||
* Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.
|
||||
* Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is often supervised learning.
|
||||
|
||||
* Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.
|
||||
* Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.
|
||||
|
||||
* Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.
|
||||
* Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Essential elements of ML
|
||||
|
||||
The methods we cover have three main topics in common, irrespective of
|
||||
whether we deal with supervised or unsupervised learning. The first
|
||||
ingredient is normally our data set (which can be subdivided into
|
||||
training and test data), the second item is a model which is normally
|
||||
a function of some parameters. The model reflects our knowledge of
|
||||
the system (or lack thereof). As an example, if we know that our data
|
||||
show a behavior similar to what would be predicted by a polynomial,
|
||||
fitting our data to a polynomial of some degree would then determin
|
||||
our model.
|
||||
whether we deal with supervised or unsupervised learning.
|
||||
* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way.
|
||||
|
||||
The last ingredient is a so-called **cost**
|
||||
function which allows us to present an estimate on how good our model
|
||||
is in reproducing the data it is supposed to train.
|
||||
* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model.
|
||||
|
||||
Here we will build our machine learning approach on elements of the
|
||||
statistical foundation discussed above, with elements from data
|
||||
analysis, stochastic processes etc. We will discuss the following
|
||||
machine learning algorithms
|
||||
* The last ingredient is a so-called **cost/loss** function (or error function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train.
|
||||
|
||||
1. Linear regression and its variants
|
||||
|
||||
2. Decision tree algorithms, from single trees to random forests
|
||||
|
||||
3. Bayesian statistics and regression
|
||||
|
||||
4. Support vector machines and finally various variants of
|
||||
|
||||
5. Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks
|
||||
|
||||
6. Networks for unsupervised learning using for example reduced Boltzmann machines.
|
||||
## An optimization/minimization problem
|
||||
|
||||
## Choice of programming language
|
||||
At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.
|
||||
|
||||
|
||||
## A Frequentist approach to data analysis
|
||||
|
||||
When you hear phrases like **predictions and estimations** and
|
||||
**correlations and causations**, what do you think of? May be you think
|
||||
of the difference between classifying new data points and generating
|
||||
new data points.
|
||||
Or perhaps you consider that correlations represent some kind of symmetric statements like
|
||||
if $A$ is correlated with $B$, then $B$ is correlated with
|
||||
$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not
|
||||
necessarily cause $A$.
|
||||
|
||||
These concepts are in some sense the difference between machine
|
||||
learning and statistics. In machine learning and prediction based
|
||||
tasks, we are often interested in developing algorithms that are
|
||||
capable of learning patterns from given data in an automated fashion,
|
||||
and then using these learned patterns to make predictions or
|
||||
assessments of newly given data. In many cases, our primary concern
|
||||
is the quality of the predictions or assessments, and we are less
|
||||
concerned about the underlying patterns that were learned in order
|
||||
to make these predictions.
|
||||
|
||||
In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),
|
||||
where the aim is to make predictions and find correlations. We focus
|
||||
less on for example extracting a probability distribution function (PDF). The PDF can be
|
||||
used in turn to make estimations and find causations such as given $A$
|
||||
what is the likelihood of finding $B$.
|
||||
|
||||
|
||||
|
||||
## What is a good model?
|
||||
|
||||
In science and engineering we often end up in situations where we want to infer (or learn) a
|
||||
quantitative model $M$ for a given set of sample points $\boldsymbol{X} \in [x_1, x_2,\dots x_N]$.
|
||||
|
||||
As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a
|
||||
straight line, or if we wish to be more sophisticated to a more complex
|
||||
function.
|
||||
|
||||
The reason for inferring such a model is that it
|
||||
serves many useful purposes. On the one hand, the model can reveal information
|
||||
encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important
|
||||
corelations that relate interesting physics interpretations.
|
||||
|
||||
In addition, it can simplify the representation of the given data set and help
|
||||
us in making predictions about future data samples.
|
||||
|
||||
A first important consideration to keep in mind is that inferring the *correct* model
|
||||
for a given data set is an elusive, if not impossible, task. The fundamental difficulty
|
||||
is that if we are not specific about what we mean by a *correct* model, there
|
||||
could easily be many different models that fit the given data set *equally well*.
|
||||
|
||||
|
||||
|
||||
## What is a good model? Can we define it?
|
||||
|
||||
|
||||
The central question is this: what leads us to say that a model is correct or
|
||||
optimal for a given data set? To make the model inference problem well posed, i.e.,
|
||||
to guarantee that there is a unique optimal model for the given data, we need to
|
||||
impose additional assumptions or restrictions on the class of models considered. To
|
||||
this end, we should not be looking for just any model that can describe the data.
|
||||
Instead, we should look for a **model** $M$ that is the best among a restricted class
|
||||
of models. In addition, to make the model inference problem computationally
|
||||
tractable, we need to specify how restricted the class of models needs to be. A
|
||||
common strategy is to start
|
||||
with the simplest possible class of models that is just necessary to describe the data
|
||||
or solve the problem at hand. More precisely, the model class should be rich enough
|
||||
to contain at least one model that can fit the data to a desired accuracy and yet be
|
||||
restricted enough that it is relatively simple to find the best model for the given data.
|
||||
|
||||
Thus, the most popular strategy is to start from the
|
||||
simplest class of models and increase the complexity of the models only when the
|
||||
simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one
|
||||
may first try the simplest class of models, namely linear models, followed obviously by more complex models.
|
||||
|
||||
How to evaluate which model fits best the data is something we will come back to over and over again in these set of lectures.
|
||||
|
||||
|
||||
|
||||
|
||||
## Choice of Programming Language
|
||||
|
||||
Python plays nowadays a central role in the development of machine
|
||||
learning techniques and tools for data analysis. In particular, seen
|
||||
@@ -212,38 +330,12 @@ Jupyter notebook framework with the possibility to run **R** codes or
|
||||
compiled programs written in C++, and much more made our choice of
|
||||
programming language for this series of lectures easy. However,
|
||||
since the focus here is not only on using existing Python libraries such
|
||||
as **Scikit-Learn** or **Tensorflow**, but also on developing your own
|
||||
as **Scikit-Learn**, **Tensorflow** and **Pytorch**, but also on developing your own
|
||||
algorithms and codes, we will as far as possible present many of these
|
||||
algorithms either as a Python codes or C++ or Fortran (or other languages) codes.
|
||||
|
||||
The reason we also focus on compiled languages like C++ (or
|
||||
Fortran), is that Python is still notoriously slow when we do not
|
||||
utilize highly streamlined computational libraries like
|
||||
[Lapack](http://www.netlib.org/lapack/) or other numerical libraries
|
||||
written in compiled languages (many of these libraries are written in
|
||||
Fortran). Although a project like [Numba](https://numba.pydata.org/)
|
||||
holds great promise for speeding up the unrolling of lengthy loops, C++
|
||||
and Fortran are presently still the performance winners. Numba gives
|
||||
you potentially the power to speed up your applications with high
|
||||
performance functions written directly in Python. In particular,
|
||||
array-oriented and math-heavy Python code can achieve similar
|
||||
performance to C, C++ and Fortran. However, even with these speed-ups,
|
||||
for codes involving heavy Markov Chain Monte Carlo analyses and
|
||||
optimizations of cost functions, C++/C or Fortran codes tend to
|
||||
outperform Python codes.
|
||||
|
||||
Presently thus, the community tends to let
|
||||
code written in C++/C or Fortran do the heavy duty numerical
|
||||
number crunching and leave the post-analysis of the data to the above
|
||||
mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen
|
||||
the changes during the last decade, the above situation may change swiftly in the not too distant future.
|
||||
|
||||
Many of the examples we discuss in this series of lectures come with
|
||||
existing data files or provide code examples which produce the data to
|
||||
be analyzed. Most of the applications we will discuss deal with
|
||||
small data sets (less than a terabyte of information) and can easily
|
||||
be analyzed and tested on standard off the shelf laptops you find in general
|
||||
stores.
|
||||
|
||||
## Data handling, machine learning and ethical aspects
|
||||
|
||||
@@ -344,7 +436,8 @@ society.
|
||||
:titlesonly:
|
||||
|
||||
|
||||
gettingstarted.ipynb
|
||||
regression.ipynb
|
||||
logistic.ipynb
|
||||
chapter2
|
||||
chapter3
|
||||
chapter4
|
||||
chapter5
|
||||
```
|
||||
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 5.1 KiB |
|
After Width: | Height: | Size: 9.8 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,544 @@
|
||||
<!-- dom:TITLE: Data Analysis and Machine Learning: Logistic Regression -->
|
||||
# Data Analysis and Machine Learning: Logistic Regression
|
||||
<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->
|
||||
<!-- Author: -->
|
||||
**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
|
||||
|
||||
Date: **Oct 17, 2019**
|
||||
|
||||
Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- !split -->
|
||||
## Logistic Regression
|
||||
|
||||
In linear regression our main interest was centered on learning the
|
||||
coefficients of a functional fit (say a polynomial) in order to be
|
||||
able to predict the response of a continuous variable on some unseen
|
||||
data. The fit to the continuous variable $y_i$ is based on some
|
||||
independent variables $\hat{x}_i$. Linear regression resulted in
|
||||
analytical expressions for standard ordinary Least Squares or Ridge
|
||||
regression (in terms of matrices to invert) for several quantities,
|
||||
ranging from the variance and thereby the confidence intervals of the
|
||||
parameters $\hat{\beta}$ to the mean squared error. If we can invert
|
||||
the product of the design matrices, linear regression gives then a
|
||||
simple recipe for fitting our data.
|
||||
|
||||
|
||||
Classification problems, however, are concerned with outcomes taking
|
||||
the form of discrete variables (i.e. categories). We may for example,
|
||||
on the basis of DNA sequencing for a number of patients, like to find
|
||||
out which mutations are important for a certain disease; or based on
|
||||
scans of various patients' brains, figure out if there is a tumor or
|
||||
not; or given a specific physical system, we'd like to identify its
|
||||
state, say whether it is an ordered or disordered system (typical
|
||||
situation in solid state physics); or classify the status of a
|
||||
patient, whether she/he has a stroke or not and many other similar
|
||||
situations.
|
||||
|
||||
The most common situation we encounter when we apply logistic
|
||||
regression is that of two possible outcomes, normally denoted as a
|
||||
binary outcome, true or false, positive or negative, success or
|
||||
failure etc.
|
||||
|
||||
## Optimization and Deep learning
|
||||
|
||||
Logistic regression will also serve as our stepping stone towards
|
||||
neural network algorithms and supervised deep learning. For logistic
|
||||
learning, the minimization of the cost function leads to a non-linear
|
||||
equation in the parameters $\hat{\beta}$. The optimization of the
|
||||
problem calls therefore for minimization algorithms. This forms the
|
||||
bottle neck of all machine learning algorithms, namely how to find
|
||||
reliable minima of a multi-variable function. This leads us to the
|
||||
family of gradient descent methods. The latter are the working horses
|
||||
of basically all modern machine learning algorithms.
|
||||
|
||||
We note also that many of the topics discussed here on logistic
|
||||
regression are also commonly used in modern supervised Deep Learning
|
||||
models, as we will see later.
|
||||
|
||||
|
||||
<!-- !split -->
|
||||
## Basics
|
||||
|
||||
We consider the case where the dependent variables, also called the
|
||||
responses or the outcomes, $y_i$ are discrete and only take values
|
||||
from $k=0,\dots,K-1$ (i.e. $K$ classes).
|
||||
|
||||
The goal is to predict the
|
||||
output classes from the design matrix $\hat{X}\in\mathbb{R}^{n\times p}$
|
||||
made of $n$ samples, each of which carries $p$ features or predictors. The
|
||||
primary goal is to identify the classes to which new unseen samples
|
||||
belong.
|
||||
|
||||
Let us specialize to the case of two classes only, with outputs
|
||||
$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a
|
||||
credit card user that could default or not on her/his credit card
|
||||
debt. That is
|
||||
|
||||
$$
|
||||
y_i = \begin{bmatrix} 0 & \mathrm{no}\\ 1 & \mathrm{yes} \end{bmatrix}.
|
||||
$$
|
||||
|
||||
## Linear classifier
|
||||
|
||||
Before moving to the logistic model, let us try to use our linear
|
||||
regression model to classify these two outcomes. We could for example
|
||||
fit a linear model to the default case if $y_i > 0.5$ and the no
|
||||
default case $y_i \leq 0.5$.
|
||||
|
||||
We would then have our
|
||||
weighted linear combination, namely
|
||||
|
||||
<!-- Equation labels as ordinary links -->
|
||||
<div id="_auto1"></div>
|
||||
|
||||
$$
|
||||
\begin{equation}
|
||||
\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon},
|
||||
\label{_auto1} \tag{1}
|
||||
\end{equation}
|
||||
$$
|
||||
|
||||
where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our
|
||||
$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors.
|
||||
|
||||
## Some selected properties
|
||||
|
||||
The main problem with our function is that it takes values on the
|
||||
entire real axis. In the case of logistic regression, however, the
|
||||
labels $y_i$ are discrete variables. A typical example is the credit
|
||||
card data discussed below here, where we can set the state of
|
||||
defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons
|
||||
in the data set (see the full example below).
|
||||
|
||||
One simple way to get a discrete output is to have sign
|
||||
functions that map the output of a linear regressor to values $\{0,1\}$,
|
||||
$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise.
|
||||
We will encounter this model in our first demonstration of neural networks. Historically it is called the "perceptron" model in the machine learning
|
||||
literature. This model is extremely simple. However, in many cases it is more
|
||||
favorable to use a ``soft" classifier that outputs
|
||||
the probability of a given category. This leads us to the logistic function.
|
||||
|
||||
|
||||
## The logistic function
|
||||
|
||||
The perceptron is an example of a ``hard classification" model. We
|
||||
will encounter this model when we discuss neural networks as
|
||||
well. Each datapoint is deterministically assigned to a category (i.e
|
||||
$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a "soft"
|
||||
classifier that outputs the probability of a given category rather
|
||||
than a single value. For example, given $x_i$, the classifier
|
||||
outputs the probability of being in a category $k$. Logistic regression
|
||||
is the most common example of a so-called soft classifier. In logistic
|
||||
regression, the probability that a data point $x_i$
|
||||
belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,
|
||||
|
||||
$$
|
||||
p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}.
|
||||
$$
|
||||
|
||||
Note that $1-p(t)= p(-t)$.
|
||||
|
||||
## Examples of likelihood functions used in logistic regression and nueral networks
|
||||
|
||||
|
||||
The following code plots the logistic function, the step function and other functions we will encounter from here and on.
|
||||
|
||||
%matplotlib inline
|
||||
|
||||
"""The sigmoid function (or the logistic curve) is a
|
||||
function that takes any real number, z, and outputs a number (0,1).
|
||||
It is useful in neural networks for assigning weights on a relative scale.
|
||||
The value z is the weighted sum of parameters involved in the learning algorithm."""
|
||||
|
||||
import numpy
|
||||
import matplotlib.pyplot as plt
|
||||
import math as mt
|
||||
|
||||
z = numpy.arange(-5, 5, .1)
|
||||
sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
|
||||
sigma = sigma_fn(z)
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
ax.plot(z, sigma)
|
||||
ax.set_ylim([-0.1, 1.1])
|
||||
ax.set_xlim([-5,5])
|
||||
ax.grid(True)
|
||||
ax.set_xlabel('z')
|
||||
ax.set_title('sigmoid function')
|
||||
|
||||
plt.show()
|
||||
|
||||
"""Step Function"""
|
||||
z = numpy.arange(-5, 5, .02)
|
||||
step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
|
||||
step = step_fn(z)
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
ax.plot(z, step)
|
||||
ax.set_ylim([-0.5, 1.5])
|
||||
ax.set_xlim([-5,5])
|
||||
ax.grid(True)
|
||||
ax.set_xlabel('z')
|
||||
ax.set_title('step function')
|
||||
|
||||
plt.show()
|
||||
|
||||
"""tanh Function"""
|
||||
z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
|
||||
t = numpy.tanh(z)
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
ax.plot(z, t)
|
||||
ax.set_ylim([-1.0, 1.0])
|
||||
ax.set_xlim([-2*mt.pi,2*mt.pi])
|
||||
ax.grid(True)
|
||||
ax.set_xlabel('z')
|
||||
ax.set_title('tanh function')
|
||||
|
||||
plt.show()
|
||||
|
||||
## Two parameters
|
||||
|
||||
We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities
|
||||
|
||||
$$
|
||||
\begin{align*}
|
||||
p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
|
||||
p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}),
|
||||
\end{align*}
|
||||
$$
|
||||
|
||||
where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$.
|
||||
|
||||
Note that we used
|
||||
|
||||
$$
|
||||
p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}).
|
||||
$$
|
||||
|
||||
<!-- !split -->
|
||||
## Maximum likelihood
|
||||
|
||||
In order to define the total likelihood for all possible outcomes from a
|
||||
dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels
|
||||
$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle.
|
||||
We aim thus at maximizing
|
||||
the probability of seeing the observed data. We can then approximate the
|
||||
likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is
|
||||
|
||||
$$
|
||||
\begin{align*}
|
||||
P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\
|
||||
\end{align*}
|
||||
$$
|
||||
|
||||
from which we obtain the log-likelihood and our **cost/loss** function
|
||||
|
||||
$$
|
||||
\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right).
|
||||
$$
|
||||
|
||||
## The cost function rewritten
|
||||
|
||||
Reordering the logarithms, we can rewrite the **cost/loss** function as
|
||||
|
||||
$$
|
||||
\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
|
||||
$$
|
||||
|
||||
The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$.
|
||||
Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that
|
||||
|
||||
$$
|
||||
\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
|
||||
$$
|
||||
|
||||
This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression,
|
||||
in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.
|
||||
|
||||
## Minimizing the cross entropy
|
||||
|
||||
The cross entropy is a convex function of the weights $\hat{\beta}$ and,
|
||||
therefore, any local minimizer is a global minimizer.
|
||||
|
||||
|
||||
Minimizing this
|
||||
cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain
|
||||
|
||||
$$
|
||||
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right),
|
||||
$$
|
||||
|
||||
and
|
||||
|
||||
$$
|
||||
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right).
|
||||
$$
|
||||
|
||||
## A more compact expression
|
||||
|
||||
Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an
|
||||
$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a
|
||||
vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first
|
||||
derivative of cost function as
|
||||
|
||||
$$
|
||||
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right).
|
||||
$$
|
||||
|
||||
If we in addition define a diagonal matrix $\hat{W}$ with elements
|
||||
$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as
|
||||
|
||||
$$
|
||||
\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}.
|
||||
$$
|
||||
|
||||
## Extending to more predictors
|
||||
|
||||
Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors
|
||||
|
||||
$$
|
||||
\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p.
|
||||
$$
|
||||
|
||||
Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to
|
||||
|
||||
$$
|
||||
p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}.
|
||||
$$
|
||||
|
||||
## Including more classes
|
||||
|
||||
Till now we have mainly focused on two classes, the so-called binary
|
||||
system. Suppose we wish to extend to $K$ classes. Let us for the sake
|
||||
of simplicity assume we have only two predictors. We have then
|
||||
following model
|
||||
|
||||
1
|
||||
5
|
||||
|
||||
<
|
||||
<
|
||||
<
|
||||
!
|
||||
!
|
||||
M
|
||||
A
|
||||
T
|
||||
H
|
||||
_
|
||||
B
|
||||
L
|
||||
O
|
||||
C
|
||||
K
|
||||
|
||||
$$
|
||||
\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1,
|
||||
$$
|
||||
|
||||
and so on till the class $C=K-1$ class
|
||||
|
||||
$$
|
||||
\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1,
|
||||
$$
|
||||
|
||||
and the model is specified in term of $K-1$ so-called log-odds or
|
||||
**logit** transformations.
|
||||
|
||||
|
||||
## More classes
|
||||
|
||||
In our discussion of neural networks we will encounter the above again
|
||||
in terms of a slightly modified function, the so-called **Softmax** function.
|
||||
|
||||
The softmax function is used in various multiclass classification
|
||||
methods, such as multinomial logistic regression (also known as
|
||||
softmax regression), multiclass linear discriminant analysis, naive
|
||||
Bayes classifiers, and artificial neural networks. Specifically, in
|
||||
multinomial logistic regression and linear discriminant analysis, the
|
||||
input to the function is the result of $K$ distinct linear functions,
|
||||
and the predicted probability for the $k$-th class given a sample
|
||||
vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two
|
||||
predictors):
|
||||
|
||||
$$
|
||||
p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}.
|
||||
$$
|
||||
|
||||
It is easy to extend to more predictors. The final class is
|
||||
|
||||
$$
|
||||
p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}},
|
||||
$$
|
||||
|
||||
and they sum to one. Our earlier discussions were all specialized to
|
||||
the case with two classes only. It is easy to see from the above that
|
||||
what we derived earlier is compatible with these equations.
|
||||
|
||||
To find the optimal parameters we would typically use a gradient
|
||||
descent method. Newton's method and gradient descent methods are
|
||||
discussed in the material on [optimization
|
||||
methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).
|
||||
|
||||
|
||||
|
||||
|
||||
## A simple classification problem
|
||||
|
||||
import numpy as np
|
||||
from sklearn import datasets, linear_model
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def generate_data():
|
||||
np.random.seed(0)
|
||||
X, y = datasets.make_moons(200, noise=0.20)
|
||||
return X, y
|
||||
|
||||
|
||||
def visualize(X, y, clf):
|
||||
plot_decision_boundary(lambda x: clf.predict(x), X, y)
|
||||
|
||||
def plot_decision_boundary(pred_func, X, y):
|
||||
# Set min and max values and give it some padding
|
||||
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
|
||||
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
|
||||
h = 0.01
|
||||
# Generate a grid of points with distance h between them
|
||||
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
|
||||
# Predict the function value for the whole gid
|
||||
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
|
||||
Z = Z.reshape(xx.shape)
|
||||
# Plot the contour and training examples
|
||||
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
|
||||
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
|
||||
plt.show()
|
||||
|
||||
|
||||
def classify(X, y):
|
||||
clf = linear_model.LogisticRegressionCV()
|
||||
clf.fit(X, y)
|
||||
return clf
|
||||
|
||||
|
||||
def main():
|
||||
X, y = generate_data()
|
||||
# visualize(X, y)
|
||||
clf = classify(X, y)
|
||||
visualize(X, y, clf)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
## The Credit Card example
|
||||
Here we use the the [credit card data](https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients).
|
||||
The data are from an extensive database from Taiwan and include more than ten predictors.
|
||||
|
||||
For categorical data -Scikit-Learn- provides a so-called **one-hot encoder**.
|
||||
This is called one-hot
|
||||
encoding, because only one attribute will be equal to 1 (hot), while the others will be 0 (cold).
|
||||
**Scikit-Learn** provides a OneHotEncoder encoder to convert integer categorical values into one-hot
|
||||
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
encoder = OneHotEncoder()
|
||||
|
||||
## How to read the Credit Card data
|
||||
|
||||
import pandas as pd
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
from sklearn.compose import ColumnTransformer
|
||||
from sklearn.preprocessing import StandardScaler, OneHotEncoder
|
||||
from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score
|
||||
|
||||
# Trying to set the seed
|
||||
np.random.seed(0)
|
||||
import random
|
||||
random.seed(0)
|
||||
|
||||
# Reading file into data frame
|
||||
cwd = os.getcwd()
|
||||
filename = cwd + '/default of credit card clients.xls'
|
||||
nanDict = {}
|
||||
df = pd.read_excel(filename, header=1, skiprows=0, index_col=0, na_values=nanDict)
|
||||
|
||||
df.rename(index=str, columns={"default payment next month": "defaultPaymentNextMonth"}, inplace=True)
|
||||
|
||||
# Features and targets
|
||||
X = df.loc[:, df.columns != 'defaultPaymentNextMonth'].values
|
||||
y = df.loc[:, df.columns == 'defaultPaymentNextMonth'].values
|
||||
|
||||
# Categorical variables to one-hot's
|
||||
onehotencoder = OneHotEncoder(categories="auto")
|
||||
|
||||
X = ColumnTransformer(
|
||||
[("", onehotencoder, [3]),],
|
||||
remainder="passthrough"
|
||||
).fit_transform(X)
|
||||
|
||||
y.shape
|
||||
|
||||
# Train-test split
|
||||
trainingShare = 0.5
|
||||
seed = 1
|
||||
XTrain, XTest, yTrain, yTest=train_test_split(X, y, train_size=trainingShare, \
|
||||
test_size = 1-trainingShare,
|
||||
random_state=seed)
|
||||
|
||||
# Input Scaling
|
||||
sc = StandardScaler()
|
||||
XTrain = sc.fit_transform(XTrain)
|
||||
XTest = sc.transform(XTest)
|
||||
|
||||
# One-hot's of the target vector
|
||||
Y_train_onehot, Y_test_onehot = onehotencoder.fit_transform(yTrain), onehotencoder.fit_transform(yTest)
|
||||
|
||||
# Remove instances with zeros only for past bill statements or paid amounts
|
||||
'''
|
||||
df = df.drop(df[(df.BILL_AMT1 == 0) &
|
||||
(df.BILL_AMT2 == 0) &
|
||||
(df.BILL_AMT3 == 0) &
|
||||
(df.BILL_AMT4 == 0) &
|
||||
(df.BILL_AMT5 == 0) &
|
||||
(df.BILL_AMT6 == 0) &
|
||||
(df.PAY_AMT1 == 0) &
|
||||
(df.PAY_AMT2 == 0) &
|
||||
(df.PAY_AMT3 == 0) &
|
||||
(df.PAY_AMT4 == 0) &
|
||||
(df.PAY_AMT5 == 0) &
|
||||
(df.PAY_AMT6 == 0)].index)
|
||||
'''
|
||||
df = df.drop(df[(df.BILL_AMT1 == 0) &
|
||||
(df.BILL_AMT2 == 0) &
|
||||
(df.BILL_AMT3 == 0) &
|
||||
(df.BILL_AMT4 == 0) &
|
||||
(df.BILL_AMT5 == 0) &
|
||||
(df.BILL_AMT6 == 0)].index)
|
||||
|
||||
df = df.drop(df[(df.PAY_AMT1 == 0) &
|
||||
(df.PAY_AMT2 == 0) &
|
||||
(df.PAY_AMT3 == 0) &
|
||||
(df.PAY_AMT4 == 0) &
|
||||
(df.PAY_AMT5 == 0) &
|
||||
(df.PAY_AMT6 == 0)].index)
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
lambdas=np.logspace(-5,7,13)
|
||||
parameters = [{'C': 1./lambdas, "solver":["lbfgs"]}]#*len(parameters)}]
|
||||
scoring = ['accuracy', 'roc_auc']
|
||||
logReg = LogisticRegression()
|
||||
gridSearch = GridSearchCV(logReg, parameters, cv=5, scoring=scoring, refit='roc_auc')
|
||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 19 KiB |
@@ -1,65 +0,0 @@
|
||||
# Content with notebooks
|
||||
|
||||
You can also create content with Jupyter Notebooks. This means that you can include
|
||||
code blocks and their outputs in your book.
|
||||
|
||||
## Markdown + notebooks
|
||||
|
||||
As it is markdown, you can embed images, HTML, etc into your posts!
|
||||
|
||||

|
||||
|
||||
You an also $add_{math}$ and
|
||||
|
||||
$$
|
||||
math^{blocks}
|
||||
$$
|
||||
|
||||
or
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
\mbox{mean} la_{tex} \\ \\
|
||||
math blocks
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
But make sure you \$Escape \$your \$dollar signs \$you want to keep!
|
||||
|
||||
## MyST markdown
|
||||
|
||||
MyST markdown works in Jupyter Notebooks as well. For more information about MyST markdown, check
|
||||
out [the MyST guide in Jupyter Book](https://jupyterbook.org/content/myst.html),
|
||||
or see [the MyST markdown documentation](https://myst-parser.readthedocs.io/en/latest/).
|
||||
|
||||
## Code blocks and outputs
|
||||
|
||||
Jupyter Book will also embed your code blocks and output in your book.
|
||||
For example, here's some sample Matplotlib code:
|
||||
|
||||
from matplotlib import rcParams, cycler
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
plt.ion()
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
N = 10
|
||||
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
|
||||
data = np.array(data).T
|
||||
cmap = plt.cm.coolwarm
|
||||
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
|
||||
|
||||
|
||||
from matplotlib.lines import Line2D
|
||||
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
|
||||
Line2D([0], [0], color=cmap(.5), lw=4),
|
||||
Line2D([0], [0], color=cmap(1.), lw=4)]
|
||||
|
||||
fig, ax = plt.subplots(figsize=(10, 5))
|
||||
lines = ax.plot(data)
|
||||
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);
|
||||
|
||||
There is a lot more that you can do with outputs (such as including interactive outputs)
|
||||
with your book. For more information about this, see [the Jupyter Book documentation](https://jupyterbook.org)
|
||||
|
Before Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 9.2 KiB |