updating lectures

This commit is contained in:
mhjensen
2020-10-04 21:32:03 +02:00
parent 3cb9aca9ba
commit 21e3a669fe
157 changed files with 31586 additions and 58823 deletions
+22
View File
@@ -0,0 +1,22 @@
translating doconce text in How2ReadData.do.txt to ipynb
*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax)
collected all required additional files in ipynb-How2ReadData-src.tar.gz which must be distributed with the notebook
*** warning: latex envir \begin{bmatrix} does not work well in Markdown.
Stick to \[ ... \], equation, equation*, align, or align*
environments in math environments.
*** warning: latex envir \begin{bmatrix} does not work well in Markdown.
Stick to \[ ... \], equation, equation*, align, or align*
environments in math environments.
*** warning: latex envir \begin{bmatrix} does not work well in Markdown.
Stick to \[ ... \], equation, equation*, align, or align*
environments in math environments.
*** warning: latex envir \begin{cases} does not work well in Markdown.
Stick to \[ ... \], equation, equation*, align, or align*
environments in math environments.
Failed to remove ans_at_end environment
Failed to remove sol_at_end environment
output in How2ReadData.ipynb
+2 -5
View File
@@ -1,10 +1,7 @@
TITLE: Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters
AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
DATE: today
======= Getting started, our first data and Machine Learning encounters =======
===== Introduction =====
===== Introduction =====
Our emphasis throughout this series of lectures
is on understanding the mathematical aspects of
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
translating doconce text in Introduction.do.txt to ipynb
*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax)
Failed to remove ans_at_end environment
Failed to remove sol_at_end environment
output in Introduction.ipynb
translating doconce text in Introduction.do.txt to ipynb
*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax)
Failed to remove ans_at_end environment
Failed to remove sol_at_end environment
output in Introduction.ipynb
+2 -33
View File
@@ -1,10 +1,4 @@
TITLE: Introduction to Applied Data Analysis and Machine Learning
AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
DATE: today
===== Introduction =====
======= Introduction to Applied Data Analysis and Machine Learning =======
During the last two decades there has been a swift and amazing
development of Machine Learning techniques and algorithms that impact
@@ -147,8 +141,6 @@ 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
@@ -164,8 +156,6 @@ 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
@@ -176,12 +166,6 @@ Carlo methods are central elements in a proper understanding of many
of the algorithms and methods we will discuss.
===== Types of Machine Learning =====
The approaches to machine learning are many, but are often split into
two main categories. In *supervised learning* we know the answer to a
problem, and let the computer deduce the logic behind it. On the other
@@ -195,35 +179,24 @@ 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:
!bpop
* 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.
* Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.
!epop
===== Essential elements of ML =====
The methods we cover have three main topics in common, irrespective of
whether we deal with supervised or unsupervised learning.
!bpop
* 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 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.
* 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.
!epop
===== An optimization/minimization problem =====
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_.
@@ -279,10 +252,6 @@ 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
Binary file not shown.
+1 -1
View File
@@ -1,4 +1,4 @@
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: 8b9f1ceca643d991eda12c1392dd2ea3
config: fdb4c65fe6fdd143bcbae649c1ee1a55
tags: 645f666f9bcd5a90fca523b33c5a78b7

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

@@ -0,0 +1 @@
details.dropdown .summary-title{padding-right:3em !important;-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;user-select:none}details.dropdown:hover{cursor:pointer}details.dropdown .summary-content{cursor:default}details.dropdown summary{list-style:none;padding:1em}details.dropdown summary .octicon.no-title{vertical-align:middle}details.dropdown[open] summary .octicon.no-title{visibility:hidden}details.dropdown summary::-webkit-details-marker{display:none}details.dropdown summary:focus{outline:none}details.dropdown summary:hover .summary-up svg,details.dropdown summary:hover .summary-down svg{opacity:1}details.dropdown .summary-up svg,details.dropdown .summary-down svg{display:block;opacity:.6}details.dropdown .summary-up,details.dropdown .summary-down{pointer-events:none;position:absolute;right:1em;top:.75em}details.dropdown[open] .summary-down{visibility:hidden}details.dropdown:not([open]) .summary-up{visibility:hidden}details.dropdown.fade-in[open] summary~*{-moz-animation:panels-fade-in .5s ease-in-out;-webkit-animation:panels-fade-in .5s ease-in-out;animation:panels-fade-in .5s ease-in-out}details.dropdown.fade-in-slide-down[open] summary~*{-moz-animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out;-webkit-animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out;animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out}@keyframes panels-fade-in{0%{opacity:0}100%{opacity:1}}@keyframes panels-slide-down{0%{transform:translate(0, -10px)}100%{transform:translate(0, 0)}}.octicon{display:inline-block;fill:currentColor;vertical-align:text-top}.tabbed-content{box-shadow:0 -.0625rem var(--tabs-color-overline),0 .0625rem var(--tabs-color-underline);display:none;order:99;padding-bottom:.75rem;padding-top:.75rem;width:100%}.tabbed-content>:first-child{margin-top:0 !important}.tabbed-content>:last-child{margin-bottom:0 !important}.tabbed-content>.tabbed-set{margin:0}.tabbed-set{border-radius:.125rem;display:flex;flex-wrap:wrap;margin:1em 0;position:relative}.tabbed-set>input{opacity:0;position:absolute}.tabbed-set>input:checked+label{border-color:var(--tabs-color-label-active);color:var(--tabs-color-label-active)}.tabbed-set>input:checked+label+.tabbed-content{display:block}.tabbed-set>input:focus+label{outline-style:auto}.tabbed-set>input:not(.focus-visible)+label{outline:none;-webkit-tap-highlight-color:transparent}.tabbed-set>label{border-bottom:.125rem solid transparent;color:var(--tabs-color-label-inactive);cursor:pointer;font-size:var(--tabs-size-label);font-weight:700;padding:1em 1.25em .5em;transition:color 250ms;width:auto;z-index:1}html .tabbed-set>label:hover{color:var(--tabs-color-label-active)}
@@ -0,0 +1,7 @@
:root {
--tabs-color-label-active: hsla(231, 99%, 66%, 1);
--tabs-color-label-inactive: rgba(178, 206, 245, 0.62);
--tabs-color-overline: rgb(207, 236, 238);
--tabs-color-underline: rgb(207, 236, 238);
--tabs-size-label: 1rem;
}
@@ -0,0 +1,404 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction to Applied Data Analysis and Machine Learning\n",
"\n",
"During the last two decades there has been a swift and amazing\n",
"development of Machine Learning techniques and algorithms that impact\n",
"many areas in not only Science and Technology but also the Humanities,\n",
"Social Sciences, Medicine, Law, indeed, almost all possible\n",
"disciplines. The applications are incredibly many, from self-driving\n",
"cars to solving high-dimensional differential equations or complicated\n",
"quantum mechanical many-body problems. Machine Learning is perceived\n",
"by many as one of the main disruptive techniques nowadays. \n",
"\n",
"Statistics, Data science and Machine Learning form important\n",
"fields of research in modern science. They describe how to learn and\n",
"make predictions from data, as well as allowing us to extract\n",
"important correlations about physical process and the underlying laws\n",
"of motion in large data sets. The latter, big data sets, appear\n",
"frequently in essentially all disciplines, from the traditional\n",
"Science, Technology, Mathematics and Engineering fields to Life\n",
"Science, Law, education research, the Humanities and the Social\n",
"Sciences.\n",
"\n",
"It has become more\n",
"and more common to see research projects on big data in for example\n",
"the Social Sciences where extracting patterns from complicated survey\n",
"data is one of many research directions. Having a solid grasp of data\n",
"analysis and machine learning is thus becoming central to scientific\n",
"computing in many fields, and competences and skills within the fields\n",
"of machine learning and scientific computing are nowadays strongly\n",
"requested by many potential employers. The latter cannot be\n",
"overstated, familiarity with machine learning has almost become a\n",
"prerequisite for many of the most exciting employment opportunities,\n",
"whether they are in bioinformatics, life science, physics or finance,\n",
"in the private or the public sector. This author has had several\n",
"students or met students who have been hired recently based on their\n",
"skills and competences in scientific computing and data science, often\n",
"with marginal knowledge of machine learning.\n",
"\n",
"Machine learning is a subfield of computer science, and is closely\n",
"related to computational statistics. It evolved from the study of\n",
"pattern recognition in artificial intelligence (AI) research, and has\n",
"made contributions to AI tasks like computer vision, natural language\n",
"processing and speech recognition. Many of the methods we will study are also \n",
"strongly rooted in basic mathematics and physics research. \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",
"Machine learning is an extremely rich field, in spite of its young\n",
"age. The increases we have seen during the last three 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 packages\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. Not all the\n",
"algorithms and methods can be given a rigorous mathematical\n",
"justification, 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 algorithms and methods we will discuss.\n",
"\n",
"\n",
"\n",
"## Learning outcomes\n",
"\n",
"These sets of lectures aim at giving you an overview of central aspects of\n",
"statistical data analysis as well as some of the central algorithms\n",
"used in machine learning. We will introduce a variety of central\n",
"algorithms and methods essential for studies of data analysis and\n",
"machine learning. \n",
"\n",
"Hands-on projects and experimenting with data and algorithms plays a central role in\n",
"these lectures, and our hope is, through the various\n",
"projects and exercises, to expose you to fundamental\n",
"research problems in these fields, with the aim to reproduce state of\n",
"the art scientific results. You will learn to develop and\n",
"structure codes for studying these systems, get acquainted with\n",
"computing facilities and learn to handle large scientific projects. A\n",
"good scientific and ethical conduct is emphasized throughout the\n",
"course. More specifically, you will\n",
"\n",
"1. Learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;\n",
"\n",
"2. Be capable of extending the acquired knowledge to other systems and cases;\n",
"\n",
"3. Have an understanding of central algorithms used in data analysis and machine learning;\n",
"\n",
"4. Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;\n",
"\n",
"5. Understand methods for regression and classification;\n",
"\n",
"6. Learn about neural network, genetic algorithms and Boltzmann machines;\n",
"\n",
"7. Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).\n",
"\n",
"There are several topics we will cover here, spanning from \n",
"statistical data analysis and its basic concepts such as expectation\n",
"values, variance, covariance, correlation functions and errors, via\n",
"well-known probability distribution functions like the uniform\n",
"distribution, the binomial distribution, the Poisson distribution and\n",
"simple and multivariate normal distributions to central elements of\n",
"Bayesian statistics and modeling. We will also remind the reader about\n",
"central elements from linear algebra and standard methods based on\n",
"linear algebra used to optimize (minimize) functions (the family of gradient descent methods)\n",
"and the Singular-value decomposition and\n",
"least square methods for parameterizing data.\n",
"\n",
"We will also cover Monte Carlo methods, Markov chains, well-known\n",
"algorithms for sampling stochastic events like the Metropolis-Hastings\n",
"and Gibbs sampling methods. An important aspect of all our\n",
"calculations is a proper estimation of errors. Here we will also\n",
"discuss famous resampling techniques like the blocking, the bootstrapping\n",
"and the jackknife methods and the infamous bias-variance tradeoff. \n",
"\n",
"The second part of the material covers several algorithms used in\n",
"machine learning.\n",
"\n",
"\n",
"\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 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",
"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",
"The approaches to machine learning are many, but are often split into\n",
"two main categories. In *supervised learning* we know the answer to a\n",
"problem, and let the computer deduce the logic behind it. On the other\n",
"hand, *unsupervised learning* is a method for finding patterns and\n",
"relationship in data sets without any prior knowledge of the system.\n",
"Some authours also operate with a third category, namely\n",
"*reinforcement learning*. This is a paradigm of learning inspired by\n",
"behavioral psychology, where learning is achieved by trial-and-error,\n",
"solely from rewards and punishment.\n",
"\n",
"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 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",
"\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",
"The methods we cover have three main topics in common, irrespective of\n",
"whether we deal with supervised or unsupervised learning.\n",
"\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 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",
"* 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",
"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",
"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",
"the wealth of machine learning and data analysis libraries written in\n",
"Python, easy to use libraries with immediate visualization(and not the\n",
"least impressive galleries of existing examples), the popularity of the\n",
"Jupyter notebook framework with the possibility to run **R** codes or\n",
"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**, **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",
"\n",
"\n",
"\n",
"## Data handling, machine learning and ethical aspects\n",
"\n",
"In most of the cases we will study, we will either generate the data\n",
"to analyze ourselves (both for supervised learning and unsupervised\n",
"learning) or we will recur again and again to data present in say\n",
"**Scikit-Learn** or **Tensorflow**. Many of the examples we end up\n",
"dealing with are from a privacy and data protection point of view,\n",
"rather inoccuous and boring results of numerical\n",
"calculations. However, this does not hinder us from developing a sound\n",
"ethical attitude to the data we use, how we analyze the data and how\n",
"we handle the data.\n",
"\n",
"The most immediate and simplest possible ethical aspects deal with our\n",
"approach to the scientific process. Nowadays, with version control\n",
"software like [Git](https://git-scm.com/) and various online\n",
"repositories like [Github](https://github.com/),\n",
"[Gitlab](https://about.gitlab.com/) etc, we can easily make our codes\n",
"and data sets we have used, freely and easily accessible to a wider\n",
"community. This helps us almost automagically in making our science\n",
"reproducible. The large open-source development communities involved\n",
"in say [Scikit-Learn](http://scikit-learn.org/stable/),\n",
"[Tensorflow](https://www.tensorflow.org/),\n",
"[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), are\n",
"all excellent examples of this. The codes can be tested and improved\n",
"upon continuosly, helping thereby our scientific community at large in\n",
"developing data analysis and machine learning tools. It is much\n",
"easier today to gain traction and acceptance for making your science\n",
"reproducible. From a societal stand, this is an important element\n",
"since many of the developers are employees of large public institutions like\n",
"universities and research labs. Our fellow taxpayers do deserve to get\n",
"something back for their bucks.\n",
"\n",
"However, this more mechanical aspect of the ethics of science (in\n",
"particular the reproducibility of scientific results) is something\n",
"which is obvious and everybody should do so as part of the dialectics of\n",
"science. The fact that many scientists are not willing to share their codes or \n",
"data is detrimental to the scientific discourse.\n",
"\n",
"Before we proceed, we should add a disclaimer. Even though\n",
"we may dream of computers developing some kind of higher learning\n",
"capabilities, at the end (even if the artificial intelligence\n",
"community keeps touting our ears full of fancy futuristic avenues), it is we, yes you reading these lines,\n",
"who end up constructing and instructing, via various algorithms, the\n",
"machine learning approaches. Self-driving cars for example, rely on sofisticated\n",
"programs which take into account all possible situations a car can\n",
"encounter. In addition, extensive usage of training data from GPS\n",
"information, maps etc, are typically fed into the software for\n",
"self-driving cars. Adding to this various sensors and cameras that\n",
"feed information to the programs, there are zillions of ethical issues\n",
"which arise from this.\n",
"\n",
"For self-driving cars, where basically many of the standard machine\n",
"learning algorithms discussed here enter into the codes, at a certain\n",
"stage we have to make choices. Yes, we , the lads and lasses who wrote\n",
"a program for a specific brand of a self-driving car. As an example,\n",
"all carmakers have as their utmost priority the security of the\n",
"driver and the accompanying passengers. A famous European carmaker, which is\n",
"one of the leaders in the market of self-driving cars, had **if**\n",
"statements of the following type: suppose there are two obstacles in\n",
"front of you and you cannot avoid to collide with one of them. One of\n",
"the obstacles is a monstertruck while the other one is a kindergarten\n",
"class trying to cross the road. The self-driving car algo would then\n",
"opt for the hitting the small folks instead of the monstertruck, since\n",
"the likelihood of surving a collision with our future citizens, is\n",
"much higher.\n",
"\n",
"This leads to serious ethical aspects. Why should we opt for such an\n",
"option? Who decides and who is entitled to make such choices? Keep in\n",
"mind that many of the algorithms you will encounter in this series of\n",
"lectures or hear about later, are indeed based on simple programming\n",
"instructions. And you are very likely to be one of the people who may\n",
"end up writing such a code. Thus, developing a sound ethical attitude\n",
"to what we do, an approach well beyond the simple mechanistic one of\n",
"making our science available and reproducible, is much needed. The\n",
"example of the self-driving cars is just one of infinitely many cases\n",
"where we have to make choices. When you analyze data on economic\n",
"inequalities, who guarantees that you are not weighting some data in a\n",
"particular way, perhaps because you dearly want a specific conclusion\n",
"which may support your political views? Or what about the recent\n",
"claims that a famous IT company like Apple has a sexist bias on the\n",
"their recently [launched credit card](https://qz.com/1748321/the-role-of-goldman-sachs-algorithms-in-the-apple-credit-card-scandal/)?\n",
"\n",
"We do not have the answers here, nor will we venture into a deeper\n",
"discussions of these aspects, but we want you think over these topics\n",
"in a more overarching way. A statistical data analysis with its dry\n",
"numbers and graphs meant to guide the eye, does not necessarily\n",
"reflect the truth, whatever that is. As a scientist, and after a\n",
"university education, you are supposedly a better citizen, with an\n",
"improved critical view and understanding of the scientific method, and\n",
"perhaps some deeper understanding of the ethics of science at\n",
"large. Use these insights. Be a critical citizen. You owe it to our\n",
"society."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -4,22 +4,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Data Analysis and Machine Learning: Logistic Regression -->\n",
"# Data Analysis and Machine Learning: Logistic Regression\n",
"<!-- 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 -->\n",
"<!-- 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: **Oct 17, 2019**\n",
"\n",
"Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"<!-- !split -->\n",
"## Logistic Regression\n",
"# Logistic Regression\n",
"\n",
"## Introduction\n",
"In linear regression our main interest was centered on learning the\n",
"coefficients of a functional fit (say a polynomial) in order to be\n",
"able to predict the response of a continuous variable on some unseen\n",
@@ -49,8 +36,6 @@
"binary outcome, true or false, positive or negative, success or\n",
"failure etc.\n",
"\n",
"## Optimization and Deep learning\n",
"\n",
"Logistic regression will also serve as our stepping stone towards\n",
"neural network algorithms and supervised deep learning. For logistic\n",
"learning, the minimization of the cost function leads to a non-linear\n",
@@ -66,7 +51,7 @@
"models, as we will see later.\n",
"\n",
"\n",
"<!-- !split -->\n",
"\n",
"## Basics\n",
"\n",
"We consider the case where the dependent variables, also called the\n",
@@ -98,8 +83,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear classifier\n",
"\n",
"Before moving to the logistic model, let us try to use our linear\n",
"regression model to classify these two outcomes. We could for example\n",
"fit a linear model to the default case if $y_i > 0.5$ and the no\n",
@@ -131,7 +114,6 @@
"where $\\hat{y}$ is a vector representing the possible outcomes, $\\hat{X}$ is our\n",
"$n\\times p$ design matrix and $\\hat{\\beta}$ represents our estimators/predictors.\n",
"\n",
"## Some selected properties\n",
"\n",
"The main problem with our function is that it takes values on the\n",
"entire real axis. In the case of logistic regression, however, the\n",
@@ -149,6 +131,7 @@
"the probability of a given category. This leads us to the logistic function.\n",
"\n",
"\n",
"\n",
"## The logistic function\n",
"\n",
"The perceptron is an example of a ``hard classification\" model. We\n",
@@ -178,8 +161,6 @@
"source": [
"Note that $1-p(t)= p(-t)$.\n",
"\n",
"## Examples of likelihood functions used in logistic regression and nueral networks\n",
"\n",
"\n",
"The following code plots the logistic function, the step function and other functions we will encounter from here and on."
]
@@ -187,7 +168,9 @@
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
@@ -291,7 +274,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## Maximum likelihood\n",
"\n",
"In order to define the total likelihood for all possible outcomes from a \n",
@@ -333,8 +315,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## The cost function rewritten\n",
"\n",
"Reordering the logarithms, we can rewrite the **cost/loss** function as"
]
},
@@ -371,7 +351,6 @@
"This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n",
"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.\n",
"\n",
"## Minimizing the cross entropy\n",
"\n",
"The cross entropy is a convex function of the weights $\\hat{\\beta}$ and,\n",
"therefore, any local minimizer is a global minimizer. \n",
@@ -410,8 +389,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## A more compact expression\n",
"\n",
"Let us now define a vector $\\hat{y}$ with $n$ elements $y_i$, an\n",
"$n\\times p$ matrix $\\hat{X}$ which contains the $x_i$ values and a\n",
"vector $\\hat{p}$ of fitted probabilities $p(y_i\\vert x_i,\\hat{\\beta})$. We can rewrite in a more compact form the first\n",
@@ -448,8 +425,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Extending to more predictors\n",
"\n",
"Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors"
]
},
@@ -547,7 +522,6 @@
"**logit** transformations.\n",
"\n",
"\n",
"## More classes\n",
"\n",
"In our discussion of neural networks we will encounter the above again\n",
"in terms of a slightly modified function, the so-called **Softmax** function.\n",
@@ -599,215 +573,11 @@
"To find the optimal parameters we would typically use a gradient\n",
"descent method. Newton's method and gradient descent methods are\n",
"discussed in the material on [optimization\n",
"methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n",
"\n",
"\n",
"\n",
"\n",
"## A simple classification problem"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from sklearn import datasets, linear_model\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"def generate_data():\n",
" np.random.seed(0)\n",
" X, y = datasets.make_moons(200, noise=0.20)\n",
" return X, y\n",
"\n",
"\n",
"def visualize(X, y, clf):\n",
" plot_decision_boundary(lambda x: clf.predict(x), X, y)\n",
"\n",
"def plot_decision_boundary(pred_func, X, y):\n",
" # Set min and max values and give it some padding\n",
" x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n",
" y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n",
" h = 0.01\n",
" # Generate a grid of points with distance h between them\n",
" xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n",
" # Predict the function value for the whole gid\n",
" Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n",
" Z = Z.reshape(xx.shape)\n",
" # Plot the contour and training examples\n",
" plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n",
" plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n",
" plt.show()\n",
"\n",
"\n",
"def classify(X, y):\n",
" clf = linear_model.LogisticRegressionCV()\n",
" clf.fit(X, y)\n",
" return clf\n",
"\n",
"\n",
"def main():\n",
" X, y = generate_data()\n",
" # visualize(X, y)\n",
" clf = classify(X, y)\n",
" visualize(X, y, clf)\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Credit Card example\n",
"Here we use the the [credit card data](https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients). \n",
"The data are from an extensive database from Taiwan and include more than ten predictors.\n",
"\n",
"For categorical data -Scikit-Learn- provides a so-called **one-hot encoder**.\n",
"This is called one-hot\n",
"encoding, because only one attribute will be equal to 1 (hot), while the others will be 0 (cold).\n",
"**Scikit-Learn** provides a OneHotEncoder encoder to convert integer categorical values into one-hot"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.preprocessing import OneHotEncoder\n",
"encoder = OneHotEncoder()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How to read the Credit Card data"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import os\n",
"import numpy as np\n",
"\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import OneHotEncoder\n",
"from sklearn.compose import ColumnTransformer\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score\n",
"\n",
"# Trying to set the seed\n",
"np.random.seed(0)\n",
"import random\n",
"random.seed(0)\n",
"\n",
"# Reading file into data frame\n",
"cwd = os.getcwd()\n",
"filename = cwd + '/default of credit card clients.xls'\n",
"nanDict = {}\n",
"df = pd.read_excel(filename, header=1, skiprows=0, index_col=0, na_values=nanDict)\n",
"\n",
"df.rename(index=str, columns={\"default payment next month\": \"defaultPaymentNextMonth\"}, inplace=True)\n",
"\n",
"# Features and targets \n",
"X = df.loc[:, df.columns != 'defaultPaymentNextMonth'].values\n",
"y = df.loc[:, df.columns == 'defaultPaymentNextMonth'].values\n",
"\n",
"# Categorical variables to one-hot's\n",
"onehotencoder = OneHotEncoder(categories=\"auto\")\n",
"\n",
"X = ColumnTransformer(\n",
" [(\"\", onehotencoder, [3]),],\n",
" remainder=\"passthrough\"\n",
").fit_transform(X)\n",
"\n",
"y.shape\n",
"\n",
"# Train-test split\n",
"trainingShare = 0.5 \n",
"seed = 1\n",
"XTrain, XTest, yTrain, yTest=train_test_split(X, y, train_size=trainingShare, \\\n",
" test_size = 1-trainingShare,\n",
" random_state=seed)\n",
"\n",
"# Input Scaling\n",
"sc = StandardScaler()\n",
"XTrain = sc.fit_transform(XTrain)\n",
"XTest = sc.transform(XTest)\n",
"\n",
"# One-hot's of the target vector\n",
"Y_train_onehot, Y_test_onehot = onehotencoder.fit_transform(yTrain), onehotencoder.fit_transform(yTest)\n",
"\n",
"# Remove instances with zeros only for past bill statements or paid amounts\n",
"'''\n",
"df = df.drop(df[(df.BILL_AMT1 == 0) &\n",
" (df.BILL_AMT2 == 0) &\n",
" (df.BILL_AMT3 == 0) &\n",
" (df.BILL_AMT4 == 0) &\n",
" (df.BILL_AMT5 == 0) &\n",
" (df.BILL_AMT6 == 0) &\n",
" (df.PAY_AMT1 == 0) &\n",
" (df.PAY_AMT2 == 0) &\n",
" (df.PAY_AMT3 == 0) &\n",
" (df.PAY_AMT4 == 0) &\n",
" (df.PAY_AMT5 == 0) &\n",
" (df.PAY_AMT6 == 0)].index)\n",
"'''\n",
"df = df.drop(df[(df.BILL_AMT1 == 0) &\n",
" (df.BILL_AMT2 == 0) &\n",
" (df.BILL_AMT3 == 0) &\n",
" (df.BILL_AMT4 == 0) &\n",
" (df.BILL_AMT5 == 0) &\n",
" (df.BILL_AMT6 == 0)].index)\n",
"\n",
"df = df.drop(df[(df.PAY_AMT1 == 0) &\n",
" (df.PAY_AMT2 == 0) &\n",
" (df.PAY_AMT3 == 0) &\n",
" (df.PAY_AMT4 == 0) &\n",
" (df.PAY_AMT5 == 0) &\n",
" (df.PAY_AMT6 == 0)].index)\n",
"\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.model_selection import GridSearchCV\n",
"\n",
"lambdas=np.logspace(-5,7,13)\n",
"parameters = [{'C': 1./lambdas, \"solver\":[\"lbfgs\"]}]#*len(parameters)}]\n",
"scoring = ['accuracy', 'roc_auc']\n",
"logReg = LogisticRegression()\n",
"gridSearch = GridSearchCV(logReg, parameters, cv=5, scoring=scoring, refit='roc_auc')"
"methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}
@@ -1,5 +0,0 @@
Content in Jupyter Book
=======================
There are many ways to write content in Jupyter Book. This short section
covers a few tips for how to do so.
@@ -1,7 +0,0 @@
Welcome to your Jupyter Book
============================
This is a small sample book to give you a feel for how book content is
structured.
Check out the content pages bundled with this sample book to get started.
@@ -1,125 +0,0 @@
# Markdown Files
Whether you write your book's content in Jupyter Notebooks (`.ipynb`) or
in regular markdown files (`.md`), you'll write in the same flavor of markdown
called **MyST Markdown**.
## What is MyST?
MyST stands for "Markedly Structured Text". It
is a slight variation on a flavor of markdown called "CommonMark" markdown,
with small syntax extensions to allow you to write **roles** and **directives**
in the Sphinx ecosystem.
## What are roles and directives?
Roles and directives are two of the most powerful tools in Jupyter Book. They
are kind of like functions, but written in a markup language. They both
serve a similar purpose, but **roles are written in one line**, whereas
**directives span many lines**. They both accept different kinds of inputs,
and what they do with those inputs depends on the specific role or directive
that is being called.
### Using a directive
At its simplest, you can insert a directive into your book's content like so:
````
```{mydirectivename}
My directive content
```
````
This will only work if a directive with name `mydirectivename` already exists
(which it doesn't). There are many pre-defined directives associated with
Jupyter Book. For example, to insert a note box into your content, you can
use the following directive:
````
```{note}
Here is a note
```
````
This results in:
```{note}
Here is a note
```
In your built book.
For more information on writing directives, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Using a role
Roles are very similar to directives, but they are less-complex and written
entirely on one line. You can insert a role into your book's content with
this pattern:
```
Some content {rolename}`and here is my role's content!`
```
Again, roles will only work if `rolename` is a valid role's name. For example,
the `doc` role can be used to refer to another page in your book. You can
refer directly to another page by its relative path. For example, the
role syntax `` {doc}`intro` `` will result in: {doc}`intro`.
For more information on writing roles, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Adding a citation
You can also cite references that are stored in a `bibtex` file. For example,
the following syntax: `` {cite}`holdgraf_evidence_2014` `` will render like
this: {cite}`holdgraf_evidence_2014`.
Moreoever, you can insert a bibliography into your page with this syntax:
The `{bibliography}` directive must be used for all the `{cite}` roles to
render properly.
For example, if the references for your book are stored in `references.bib`,
then the bibliography is inserted with:
````
```{bibliography} references.bib
```
````
Resulting in a rendered bibliography that looks like:
```{bibliography} references.bib
```
### Executing code in your markdown files
If you'd like to include computational content inside these markdown files,
you can use MyST Markdown to define cells that will be executed when your
book is built. Jupyter Book uses *jupytext* to do this.
First, add Jupytext metadata to the file. For example, to add Jupytext metadata
to this markdown page, run this command:
```
jupyter-book myst init markdown.md
```
Once a markdown file has Jupytext metadata in it, you can add the following
directive to run the code at build time:
````
```{code-cell}
print("Here is some code to execute")
```
````
When your book is built, the contents of any `{code-cell}` blocks will be
executed with your default Jupyter kernel, and their outputs will be displayed
in-line with the rest of your content.
For more information about executing computational content with Jupyter Book,
see [The MyST-NB documentation](https://myst-nb.readthedocs.io/).
@@ -1,122 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Content with notebooks\n",
"\n",
"You can also create content with Jupyter Notebooks. This means that you can include\n",
"code blocks and their outputs in your book.\n",
"\n",
"## Markdown + notebooks\n",
"\n",
"As it is markdown, you can embed images, HTML, etc into your posts!\n",
"\n",
"![](https://myst-parser.readthedocs.io/en/latest/_static/logo.png)\n",
"\n",
"You an also $add_{math}$ and\n",
"\n",
"$$\n",
"math^{blocks}\n",
"$$\n",
"\n",
"or\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mbox{mean} la_{tex} \\\\ \\\\\n",
"math blocks\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"But make sure you \\$Escape \\$your \\$dollar signs \\$you want to keep!\n",
"\n",
"## MyST markdown\n",
"\n",
"MyST markdown works in Jupyter Notebooks as well. For more information about MyST markdown, check\n",
"out [the MyST guide in Jupyter Book](https://jupyterbook.org/content/myst.html),\n",
"or see [the MyST markdown documentation](https://myst-parser.readthedocs.io/en/latest/).\n",
"\n",
"## Code blocks and outputs\n",
"\n",
"Jupyter Book will also embed your code blocks and output in your book.\n",
"For example, here's some sample Matplotlib code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import rcParams, cycler\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"plt.ion()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fixing random state for reproducibility\n",
"np.random.seed(19680801)\n",
"\n",
"N = 10\n",
"data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]\n",
"data = np.array(data).T\n",
"cmap = plt.cm.coolwarm\n",
"rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))\n",
"\n",
"\n",
"from matplotlib.lines import Line2D\n",
"custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),\n",
" Line2D([0], [0], color=cmap(.5), lw=4),\n",
" Line2D([0], [0], color=cmap(1.), lw=4)]\n",
"\n",
"fig, ax = plt.subplots(figsize=(10, 5))\n",
"lines = ax.plot(data)\n",
"ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is a lot more that you can do with outputs (such as including interactive outputs)\n",
"with your book. For more information about this, see [the Jupyter Book documentation](https://jupyterbook.org)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.0"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

@@ -0,0 +1 @@
details.dropdown .summary-title{padding-right:3em !important;-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;user-select:none}details.dropdown:hover{cursor:pointer}details.dropdown .summary-content{cursor:default}details.dropdown summary{list-style:none;padding:1em}details.dropdown summary .octicon.no-title{vertical-align:middle}details.dropdown[open] summary .octicon.no-title{visibility:hidden}details.dropdown summary::-webkit-details-marker{display:none}details.dropdown summary:focus{outline:none}details.dropdown summary:hover .summary-up svg,details.dropdown summary:hover .summary-down svg{opacity:1}details.dropdown .summary-up svg,details.dropdown .summary-down svg{display:block;opacity:.6}details.dropdown .summary-up,details.dropdown .summary-down{pointer-events:none;position:absolute;right:1em;top:.75em}details.dropdown[open] .summary-down{visibility:hidden}details.dropdown:not([open]) .summary-up{visibility:hidden}details.dropdown.fade-in[open] summary~*{-moz-animation:panels-fade-in .5s ease-in-out;-webkit-animation:panels-fade-in .5s ease-in-out;animation:panels-fade-in .5s ease-in-out}details.dropdown.fade-in-slide-down[open] summary~*{-moz-animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out;-webkit-animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out;animation:panels-fade-in .5s ease-in-out, panels-slide-down .5s ease-in-out}@keyframes panels-fade-in{0%{opacity:0}100%{opacity:1}}@keyframes panels-slide-down{0%{transform:translate(0, -10px)}100%{transform:translate(0, 0)}}.octicon{display:inline-block;fill:currentColor;vertical-align:text-top}.tabbed-content{box-shadow:0 -.0625rem var(--tabs-color-overline),0 .0625rem var(--tabs-color-underline);display:none;order:99;padding-bottom:.75rem;padding-top:.75rem;width:100%}.tabbed-content>:first-child{margin-top:0 !important}.tabbed-content>:last-child{margin-bottom:0 !important}.tabbed-content>.tabbed-set{margin:0}.tabbed-set{border-radius:.125rem;display:flex;flex-wrap:wrap;margin:1em 0;position:relative}.tabbed-set>input{opacity:0;position:absolute}.tabbed-set>input:checked+label{border-color:var(--tabs-color-label-active);color:var(--tabs-color-label-active)}.tabbed-set>input:checked+label+.tabbed-content{display:block}.tabbed-set>input:focus+label{outline-style:auto}.tabbed-set>input:not(.focus-visible)+label{outline:none;-webkit-tap-highlight-color:transparent}.tabbed-set>label{border-bottom:.125rem solid transparent;color:var(--tabs-color-label-inactive);cursor:pointer;font-size:var(--tabs-size-label);font-weight:700;padding:1em 1.25em .5em;transition:color 250ms;width:auto;z-index:1}html .tabbed-set>label:hover{color:var(--tabs-color-label-active)}
@@ -0,0 +1,7 @@
:root {
--tabs-color-label-active: hsla(231, 99%, 66%, 1);
--tabs-color-label-inactive: rgba(178, 206, 245, 0.62);
--tabs-color-overline: rgb(207, 236, 238);
--tabs-color-underline: rgb(207, 236, 238);
--tabs-size-label: 1rem;
}
@@ -0,0 +1,608 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to Applied Data Analysis and Machine Learning &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="1. Getting started, our first data and Machine Learning encounters" href="chapter2.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="#">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/chapter1.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#learning-outcomes">
Learning outcomes
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#machine-learning-a-small-and-probably-biased-introduction">
Machine Learning, a small (and probably biased) introduction
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#a-frequentist-approach-to-data-analysis">
A Frequentist approach to data analysis
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#what-is-a-good-model">
What is a good model?
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#choice-of-programming-language">
Choice of Programming Language
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#data-handling-machine-learning-and-ethical-aspects">
Data handling, machine learning and ethical aspects
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="introduction-to-applied-data-analysis-and-machine-learning">
<h1>Introduction to Applied Data Analysis and Machine Learning<a class="headerlink" href="#introduction-to-applied-data-analysis-and-machine-learning" title="Permalink to this headline"></a></h1>
<p>During the last two decades there has been a swift and amazing
development of Machine Learning techniques and algorithms that impact
many areas in not only Science and Technology but also the Humanities,
Social Sciences, Medicine, Law, indeed, almost all possible
disciplines. The applications are incredibly many, from self-driving
cars to solving high-dimensional differential equations or complicated
quantum mechanical many-body problems. Machine Learning is perceived
by many as one of the main disruptive techniques nowadays.</p>
<p>Statistics, Data science and Machine Learning form important
fields of research in modern science. They describe how to learn and
make predictions from data, as well as allowing us to extract
important correlations about physical process and the underlying laws
of motion in large data sets. The latter, big data sets, appear
frequently in essentially all disciplines, from the traditional
Science, Technology, Mathematics and Engineering fields to Life
Science, Law, education research, the Humanities and the Social
Sciences.</p>
<p>It has become more
and more common to see research projects on big data in for example
the Social Sciences where extracting patterns from complicated survey
data is one of many research directions. Having a solid grasp of data
analysis and machine learning is thus becoming central to scientific
computing in many fields, and competences and skills within the fields
of machine learning and scientific computing are nowadays strongly
requested by many potential employers. The latter cannot be
overstated, familiarity with machine learning has almost become a
prerequisite for many of the most exciting employment opportunities,
whether they are in bioinformatics, life science, physics or finance,
in the private or the public sector. This author has had several
students or met students who have been hired recently based on their
skills and competences in scientific computing and data science, often
with marginal knowledge of machine learning.</p>
<p>Machine learning is a subfield of computer science, and is closely
related to computational statistics. It evolved from the study of
pattern recognition in artificial intelligence (AI) research, and has
made contributions to AI tasks like computer vision, natural language
processing and speech recognition. Many of the methods we will study are also
strongly rooted in basic mathematics and physics research.</p>
<p>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.</p>
<p>Machine learning is an extremely rich field, in spite of its young
age. The increases we have seen during the last three 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 packages
written in Python for machine learning like
<a class="reference external" href="http://scikit-learn.org/stable/">Scikit-learn</a>,
<a class="reference external" href="https://www.tensorflow.org/">Tensorflow</a>,
<a class="reference external" href="http://pytorch.org/">PyTorch</a> and <a class="reference external" href="https://keras.io/">Keras</a>, 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. Not all the
algorithms and methods can be given a rigorous mathematical
justification, 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 algorithms and methods we will discuss.</p>
<div class="section" id="learning-outcomes">
<h2>Learning outcomes<a class="headerlink" href="#learning-outcomes" title="Permalink to this headline"></a></h2>
<p>These sets of lectures aim at giving you an overview of central aspects of
statistical data analysis as well as some of the central algorithms
used in machine learning. We will introduce a variety of central
algorithms and methods essential for studies of data analysis and
machine learning.</p>
<p>Hands-on projects and experimenting with data and algorithms plays a central role in
these lectures, and our hope is, through the various
projects and exercises, to expose you to fundamental
research problems in these fields, with the aim to reproduce state of
the art scientific results. You will learn to develop and
structure codes for studying these systems, get acquainted with
computing facilities and learn to handle large scientific projects. A
good scientific and ethical conduct is emphasized throughout the
course. More specifically, you will</p>
<ol class="simple">
<li><p>Learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;</p></li>
<li><p>Be capable of extending the acquired knowledge to other systems and cases;</p></li>
<li><p>Have an understanding of central algorithms used in data analysis and machine learning;</p></li>
<li><p>Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;</p></li>
<li><p>Understand methods for regression and classification;</p></li>
<li><p>Learn about neural network, genetic algorithms and Boltzmann machines;</p></li>
<li><p>Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).</p></li>
</ol>
<p>There are several topics we will cover here, spanning from
statistical data analysis and its basic concepts such as expectation
values, variance, covariance, correlation functions and errors, via
well-known probability distribution functions like the uniform
distribution, the binomial distribution, the Poisson distribution and
simple and multivariate normal distributions to central elements of
Bayesian statistics and modeling. We will also remind the reader about
central elements from linear algebra and standard methods based on
linear algebra used to optimize (minimize) functions (the family of gradient descent methods)
and the Singular-value decomposition and
least square methods for parameterizing data.</p>
<p>We will also cover Monte Carlo methods, Markov chains, well-known
algorithms for sampling stochastic events like the Metropolis-Hastings
and Gibbs sampling methods. An important aspect of all our
calculations is a proper estimation of errors. Here we will also
discuss famous resampling techniques like the blocking, the bootstrapping
and the jackknife methods and the infamous bias-variance tradeoff.</p>
<p>The second part of the material covers several algorithms used in
machine learning.</p>
</div>
<div class="section" id="machine-learning-a-small-and-probably-biased-introduction">
<h2>Machine Learning, a small (and probably biased) introduction<a class="headerlink" href="#machine-learning-a-small-and-probably-biased-introduction" title="Permalink to this headline"></a></h2>
<p>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.</p>
<p>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
<a class="reference external" href="http://scikit-learn.org/stable/">Scikit-learn</a>,
<a class="reference external" href="https://www.tensorflow.org/">Tensorflow</a>,
<a class="reference external" href="http://pytorch.org/">PyTorch</a> and <a class="reference external" href="https://keras.io/">Keras</a>, 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.</p>
<p>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.</p>
<p>The approaches to machine learning are many, but are often split into
two main categories. In <em>supervised learning</em> we know the answer to a
problem, and let the computer deduce the logic behind it. On the other
hand, <em>unsupervised learning</em> is a method for finding patterns and
relationship in data sets without any prior knowledge of the system.
Some authours also operate with a third category, namely
<em>reinforcement learning</em>. This is a paradigm of learning inspired by
behavioral psychology, where learning is achieved by trial-and-error,
solely from rewards and punishment.</p>
<p>Another way to categorize machine learning tasks is to consider the
desired output of a system. Some of the most common tasks are:</p>
<ul class="simple">
<li><p>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.</p></li>
<li><p>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.</p></li>
<li><p>Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.</p></li>
</ul>
<p>The methods we cover have three main topics in common, irrespective of
whether we deal with supervised or unsupervised learning.</p>
<ul class="simple">
<li><p>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.</p></li>
<li><p>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.</p></li>
<li><p>The last ingredient is a so-called <strong>cost/loss</strong> 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.</p></li>
</ul>
<p>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 <strong>gradient methods</strong>.</p>
</div>
<div class="section" id="a-frequentist-approach-to-data-analysis">
<h2>A Frequentist approach to data analysis<a class="headerlink" href="#a-frequentist-approach-to-data-analysis" title="Permalink to this headline"></a></h2>
<p>When you hear phrases like <strong>predictions and estimations</strong> and
<strong>correlations and causations</strong>, 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 <span class="math notranslate nohighlight">\(A\)</span> is correlated with <span class="math notranslate nohighlight">\(B\)</span>, then <span class="math notranslate nohighlight">\(B\)</span> is correlated with
<span class="math notranslate nohighlight">\(A\)</span>. Causation on the other hand is directional, that is if <span class="math notranslate nohighlight">\(A\)</span> causes <span class="math notranslate nohighlight">\(B\)</span>, <span class="math notranslate nohighlight">\(B\)</span> does not
necessarily cause <span class="math notranslate nohighlight">\(A\)</span>.</p>
<p>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.</p>
<p>In machine learning we normally use <a class="reference external" href="https://en.wikipedia.org/wiki/Frequentist_inference">a so-called frequentist approach</a>,
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 <span class="math notranslate nohighlight">\(A\)</span>
what is the likelihood of finding <span class="math notranslate nohighlight">\(B\)</span>.</p>
</div>
<div class="section" id="what-is-a-good-model">
<h2>What is a good model?<a class="headerlink" href="#what-is-a-good-model" title="Permalink to this headline"></a></h2>
<p>In science and engineering we often end up in situations where we want to infer (or learn) a
quantitative model <span class="math notranslate nohighlight">\(M\)</span> for a given set of sample points <span class="math notranslate nohighlight">\(\boldsymbol{X} \in [x_1, x_2,\dots x_N]\)</span>.</p>
<p>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.</p>
<p>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.</p>
<p>In addition, it can simplify the representation of the given data set and help
us in making predictions about future data samples.</p>
<p>A first important consideration to keep in mind is that inferring the <em>correct</em> 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 <em>correct</em> model, there
could easily be many different models that fit the given data set <em>equally well</em>.</p>
<p>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 <strong>model</strong> <span class="math notranslate nohighlight">\(M\)</span> 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.</p>
<p>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.</p>
<p>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.</p>
</div>
<div class="section" id="choice-of-programming-language">
<h2>Choice of Programming Language<a class="headerlink" href="#choice-of-programming-language" title="Permalink to this headline"></a></h2>
<p>Python plays nowadays a central role in the development of machine
learning techniques and tools for data analysis. In particular, seen
the wealth of machine learning and data analysis libraries written in
Python, easy to use libraries with immediate visualization(and not the
least impressive galleries of existing examples), the popularity of the
Jupyter notebook framework with the possibility to run <strong>R</strong> 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 <strong>Scikit-Learn</strong>, <strong>Tensorflow</strong> and <strong>Pytorch</strong>, 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.</p>
</div>
<div class="section" id="data-handling-machine-learning-and-ethical-aspects">
<h2>Data handling, machine learning and ethical aspects<a class="headerlink" href="#data-handling-machine-learning-and-ethical-aspects" title="Permalink to this headline"></a></h2>
<p>In most of the cases we will study, we will either generate the data
to analyze ourselves (both for supervised learning and unsupervised
learning) or we will recur again and again to data present in say
<strong>Scikit-Learn</strong> or <strong>Tensorflow</strong>. Many of the examples we end up
dealing with are from a privacy and data protection point of view,
rather inoccuous and boring results of numerical
calculations. However, this does not hinder us from developing a sound
ethical attitude to the data we use, how we analyze the data and how
we handle the data.</p>
<p>The most immediate and simplest possible ethical aspects deal with our
approach to the scientific process. Nowadays, with version control
software like <a class="reference external" href="https://git-scm.com/">Git</a> and various online
repositories like <a class="reference external" href="https://github.com/">Github</a>,
<a class="reference external" href="https://about.gitlab.com/">Gitlab</a> etc, we can easily make our codes
and data sets we have used, freely and easily accessible to a wider
community. This helps us almost automagically in making our science
reproducible. The large open-source development communities involved
in say <a class="reference external" href="http://scikit-learn.org/stable/">Scikit-Learn</a>,
<a class="reference external" href="https://www.tensorflow.org/">Tensorflow</a>,
<a class="reference external" href="http://pytorch.org/">PyTorch</a> and <a class="reference external" href="https://keras.io/">Keras</a>, are
all excellent examples of this. The codes can be tested and improved
upon continuosly, helping thereby our scientific community at large in
developing data analysis and machine learning tools. It is much
easier today to gain traction and acceptance for making your science
reproducible. From a societal stand, this is an important element
since many of the developers are employees of large public institutions like
universities and research labs. Our fellow taxpayers do deserve to get
something back for their bucks.</p>
<p>However, this more mechanical aspect of the ethics of science (in
particular the reproducibility of scientific results) is something
which is obvious and everybody should do so as part of the dialectics of
science. The fact that many scientists are not willing to share their codes or
data is detrimental to the scientific discourse.</p>
<p>Before we proceed, we should add a disclaimer. Even though
we may dream of computers developing some kind of higher learning
capabilities, at the end (even if the artificial intelligence
community keeps touting our ears full of fancy futuristic avenues), it is we, yes you reading these lines,
who end up constructing and instructing, via various algorithms, the
machine learning approaches. Self-driving cars for example, rely on sofisticated
programs which take into account all possible situations a car can
encounter. In addition, extensive usage of training data from GPS
information, maps etc, are typically fed into the software for
self-driving cars. Adding to this various sensors and cameras that
feed information to the programs, there are zillions of ethical issues
which arise from this.</p>
<p>For self-driving cars, where basically many of the standard machine
learning algorithms discussed here enter into the codes, at a certain
stage we have to make choices. Yes, we , the lads and lasses who wrote
a program for a specific brand of a self-driving car. As an example,
all carmakers have as their utmost priority the security of the
driver and the accompanying passengers. A famous European carmaker, which is
one of the leaders in the market of self-driving cars, had <strong>if</strong>
statements of the following type: suppose there are two obstacles in
front of you and you cannot avoid to collide with one of them. One of
the obstacles is a monstertruck while the other one is a kindergarten
class trying to cross the road. The self-driving car algo would then
opt for the hitting the small folks instead of the monstertruck, since
the likelihood of surving a collision with our future citizens, is
much higher.</p>
<p>This leads to serious ethical aspects. Why should we opt for such an
option? Who decides and who is entitled to make such choices? Keep in
mind that many of the algorithms you will encounter in this series of
lectures or hear about later, are indeed based on simple programming
instructions. And you are very likely to be one of the people who may
end up writing such a code. Thus, developing a sound ethical attitude
to what we do, an approach well beyond the simple mechanistic one of
making our science available and reproducible, is much needed. The
example of the self-driving cars is just one of infinitely many cases
where we have to make choices. When you analyze data on economic
inequalities, who guarantees that you are not weighting some data in a
particular way, perhaps because you dearly want a specific conclusion
which may support your political views? Or what about the recent
claims that a famous IT company like Apple has a sexist bias on the
their recently <a class="reference external" href="https://qz.com/1748321/the-role-of-goldman-sachs-algorithms-in-the-apple-credit-card-scandal/">launched credit card</a>?</p>
<p>We do not have the answers here, nor will we venture into a deeper
discussions of these aspects, but we want you think over these topics
in a more overarching way. A statistical data analysis with its dry
numbers and graphs meant to guide the eye, does not necessarily
reflect the truth, whatever that is. As a scientist, and after a
university education, you are supposedly a better citizen, with an
improved critical view and understanding of the scientific method, and
perhaps some deeper understanding of the ethics of science at
large. Use these insights. Be a critical citizen. You owe it to our
society.</p>
<div class="toctree-wrapper compound">
</div>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='right-next' id="next-link" href="chapter2.html" title="next page"><span class="section-number">1. </span>Getting started, our first data and Machine Learning encounters</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,598 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3. Logistic Regression &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="prev" title="2. Linear Regression and more Advanced Regression Analysis" href="chapter3.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<ul class="current nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
3. Logistic Regression
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/chapter4.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#introduction">
3.1. Introduction
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#basics">
3.2. Basics
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-logistic-function">
3.3. The logistic function
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#two-parameters">
3.4. Two parameters
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#maximum-likelihood">
3.5. Maximum likelihood
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#including-more-classes">
3.6. Including more classes
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="logistic-regression">
<h1><span class="section-number">3. </span>Logistic Regression<a class="headerlink" href="#logistic-regression" title="Permalink to this headline"></a></h1>
<div class="section" id="introduction">
<h2><span class="section-number">3.1. </span>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline"></a></h2>
<p>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 <span class="math notranslate nohighlight">\(y_i\)</span> is based on some
independent variables <span class="math notranslate nohighlight">\(\hat{x}_i\)</span>. 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 <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> 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.</p>
<p>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, wed 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.</p>
<p>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.</p>
<p>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 <span class="math notranslate nohighlight">\(\hat{\beta}\)</span>. 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.</p>
<p>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.</p>
</div>
<div class="section" id="basics">
<h2><span class="section-number">3.2. </span>Basics<a class="headerlink" href="#basics" title="Permalink to this headline"></a></h2>
<p>We consider the case where the dependent variables, also called the
responses or the outcomes, <span class="math notranslate nohighlight">\(y_i\)</span> are discrete and only take values
from <span class="math notranslate nohighlight">\(k=0,\dots,K-1\)</span> (i.e. <span class="math notranslate nohighlight">\(K\)</span> classes).</p>
<p>The goal is to predict the
output classes from the design matrix <span class="math notranslate nohighlight">\(\hat{X}\in\mathbb{R}^{n\times p}\)</span>
made of <span class="math notranslate nohighlight">\(n\)</span> samples, each of which carries <span class="math notranslate nohighlight">\(p\)</span> features or predictors. The
primary goal is to identify the classes to which new unseen samples
belong.</p>
<p>Let us specialize to the case of two classes only, with outputs
<span class="math notranslate nohighlight">\(y_i=0\)</span> and <span class="math notranslate nohighlight">\(y_i=1\)</span>. Our outcomes could represent the status of a
credit card user that could default or not on her/his credit card
debt. That is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
y_i = \begin{bmatrix} 0 &amp; \mathrm{no}\\ 1 &amp; \mathrm{yes} \end{bmatrix}.
\end{split}\]</div>
<p>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 <span class="math notranslate nohighlight">\(y_i &gt; 0.5\)</span> and the no
default case <span class="math notranslate nohighlight">\(y_i \leq 0.5\)</span>.</p>
<p>We would then have our
weighted linear combination, namely</p>
<!-- Equation labels as ordinary links -->
<div id="_auto1"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}
\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon},
\label{_auto1} \tag{1}
\end{equation}
\]</div>
<p>where <span class="math notranslate nohighlight">\(\hat{y}\)</span> is a vector representing the possible outcomes, <span class="math notranslate nohighlight">\(\hat{X}\)</span> is our
<span class="math notranslate nohighlight">\(n\times p\)</span> design matrix and <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> represents our estimators/predictors.</p>
<p>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 <span class="math notranslate nohighlight">\(y_i\)</span> 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 <span class="math notranslate nohighlight">\(y_i=1\)</span> and not to <span class="math notranslate nohighlight">\(y_i=0\)</span> for one the persons
in the data set (see the full example below).</p>
<p>One simple way to get a discrete output is to have sign
functions that map the output of a linear regressor to values <span class="math notranslate nohighlight">\(\{0,1\}\)</span>,
<span class="math notranslate nohighlight">\(f(s_i)=sign(s_i)=1\)</span> if <span class="math notranslate nohighlight">\(s_i\ge 0\)</span> 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.</p>
</div>
<div class="section" id="the-logistic-function">
<h2><span class="section-number">3.3. </span>The logistic function<a class="headerlink" href="#the-logistic-function" title="Permalink to this headline"></a></h2>
<p>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
<span class="math notranslate nohighlight">\(y_i=0\)</span> or <span class="math notranslate nohighlight">\(y_i=1\)</span>). 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 <span class="math notranslate nohighlight">\(x_i\)</span>, the classifier
outputs the probability of being in a category <span class="math notranslate nohighlight">\(k\)</span>. Logistic regression
is the most common example of a so-called soft classifier. In logistic
regression, the probability that a data point <span class="math notranslate nohighlight">\(x_i\)</span>
belongs to a category <span class="math notranslate nohighlight">\(y_i=\{0,1\}\)</span> is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,</p>
<div class="math notranslate nohighlight">
\[
p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}.
\]</div>
<p>Note that <span class="math notranslate nohighlight">\(1-p(t)= p(-t)\)</span>.</p>
<p>The following code plots the logistic function, the step function and other functions we will encounter from here and on.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="sd">&quot;&quot;&quot;The sigmoid function (or the logistic curve) is a</span>
<span class="sd">function that takes any real number, z, and outputs a number (0,1).</span>
<span class="sd">It is useful in neural networks for assigning weights on a relative scale.</span>
<span class="sd">The value z is the weighted sum of parameters involved in the learning algorithm.&quot;&quot;&quot;</span>
<span class="kn">import</span> <span class="nn">numpy</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">math</span> <span class="k">as</span> <span class="nn">mt</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">)</span>
<span class="n">sigma_fn</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">vectorize</span><span class="p">(</span><span class="k">lambda</span> <span class="n">z</span><span class="p">:</span> <span class="mi">1</span><span class="o">/</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="n">numpy</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">z</span><span class="p">)))</span>
<span class="n">sigma</span> <span class="o">=</span> <span class="n">sigma_fn</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">sigma</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">1.1</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;sigmoid function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="sd">&quot;&quot;&quot;Step Function&quot;&quot;&quot;</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">.</span><span class="mi">02</span><span class="p">)</span>
<span class="n">step_fn</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">vectorize</span><span class="p">(</span><span class="k">lambda</span> <span class="n">z</span><span class="p">:</span> <span class="mf">1.0</span> <span class="k">if</span> <span class="n">z</span> <span class="o">&gt;=</span> <span class="mf">0.0</span> <span class="k">else</span> <span class="mf">0.0</span><span class="p">)</span>
<span class="n">step</span> <span class="o">=</span> <span class="n">step_fn</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">step</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;step function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="sd">&quot;&quot;&quot;tanh Function&quot;&quot;&quot;</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">)</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">tanh</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;tanh function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/chapter4_7_0.png" src="_images/chapter4_7_0.png" />
<img alt="_images/chapter4_7_1.png" src="_images/chapter4_7_1.png" />
<img alt="_images/chapter4_7_2.png" src="_images/chapter4_7_2.png" />
</div>
</div>
</div>
<div class="section" id="two-parameters">
<h2><span class="section-number">3.4. </span>Two parameters<a class="headerlink" href="#two-parameters" title="Permalink to this headline"></a></h2>
<p>We assume now that we have two classes with <span class="math notranslate nohighlight">\(y_i\)</span> either <span class="math notranslate nohighlight">\(0\)</span> or <span class="math notranslate nohighlight">\(1\)</span>. Furthermore we assume also that we have only two parameters <span class="math notranslate nohighlight">\(\beta\)</span> in our fitting of the Sigmoid function, that is we define probabilities</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*}
p(y_i=1|x_i,\hat{\beta}) &amp;= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
p(y_i=0|x_i,\hat{\beta}) &amp;= 1 - p(y_i=1|x_i,\hat{\beta}),
\end{align*}
\end{split}\]</div>
<p>where <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> are the weights we wish to extract from data, in our case <span class="math notranslate nohighlight">\(\beta_0\)</span> and <span class="math notranslate nohighlight">\(\beta_1\)</span>.</p>
<p>Note that we used</p>
<div class="math notranslate nohighlight">
\[
p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}).
\]</div>
</div>
<div class="section" id="maximum-likelihood">
<h2><span class="section-number">3.5. </span>Maximum likelihood<a class="headerlink" href="#maximum-likelihood" title="Permalink to this headline"></a></h2>
<p>In order to define the total likelihood for all possible outcomes from a<br />
dataset <span class="math notranslate nohighlight">\(\mathcal{D}=\{(y_i,x_i)\}\)</span>, with the binary labels
<span class="math notranslate nohighlight">\(y_i\in\{0,1\}\)</span> and where the data points are drawn independently, we use the so-called <a class="reference external" href="https://en.wikipedia.org/wiki/Maximum_likelihood_estimation">Maximum Likelihood Estimation</a> (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 <span class="math notranslate nohighlight">\(y_i\)</span>, that is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*}
P(\mathcal{D}|\hat{\beta})&amp; = \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*}
\end{split}\]</div>
<p>from which we obtain the log-likelihood and our <strong>cost/loss</strong> function</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>Reordering the logarithms, we can rewrite the <strong>cost/loss</strong> function as</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to <span class="math notranslate nohighlight">\(\beta\)</span>.
Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>This equation is known in statistics as the <strong>cross entropy</strong>. Finally, we note that just as in linear regression,
in practice we often supplement the cross-entropy with additional regularization terms, usually <span class="math notranslate nohighlight">\(L_1\)</span> and <span class="math notranslate nohighlight">\(L_2\)</span> regularization as we did for Ridge and Lasso regression.</p>
<p>The cross entropy is a convex function of the weights <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> and,
therefore, any local minimizer is a global minimizer.</p>
<p>Minimizing this
cost function with respect to the two parameters <span class="math notranslate nohighlight">\(\beta_0\)</span> and <span class="math notranslate nohighlight">\(\beta_1\)</span> we obtain</p>
<div class="math notranslate nohighlight">
\[
\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),
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>Let us now define a vector <span class="math notranslate nohighlight">\(\hat{y}\)</span> with <span class="math notranslate nohighlight">\(n\)</span> elements <span class="math notranslate nohighlight">\(y_i\)</span>, an
<span class="math notranslate nohighlight">\(n\times p\)</span> matrix <span class="math notranslate nohighlight">\(\hat{X}\)</span> which contains the <span class="math notranslate nohighlight">\(x_i\)</span> values and a
vector <span class="math notranslate nohighlight">\(\hat{p}\)</span> of fitted probabilities <span class="math notranslate nohighlight">\(p(y_i\vert x_i,\hat{\beta})\)</span>. We can rewrite in a more compact form the first
derivative of cost function as</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right).
\]</div>
<p>If we in addition define a diagonal matrix <span class="math notranslate nohighlight">\(\hat{W}\)</span> with elements
<span class="math notranslate nohighlight">\(p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})\)</span>, we can obtain a compact expression of the second derivative as</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}.
\]</div>
<p>Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with <span class="math notranslate nohighlight">\(p\)</span> predictors</p>
<div class="math notranslate nohighlight">
\[
\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.
\]</div>
<p>Here we defined <span class="math notranslate nohighlight">\(\hat{x}=[1,x_1,x_2,\dots,x_p]\)</span> and <span class="math notranslate nohighlight">\(\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]\)</span> leading to</p>
<div class="math notranslate nohighlight">
\[
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)}}.
\]</div>
</div>
<div class="section" id="including-more-classes">
<h2><span class="section-number">3.6. </span>Including more classes<a class="headerlink" href="#including-more-classes" title="Permalink to this headline"></a></h2>
<p>Till now we have mainly focused on two classes, the so-called binary
system. Suppose we wish to extend to <span class="math notranslate nohighlight">\(K\)</span> classes. Let us for the sake
of simplicity assume we have only two predictors. We have then
following model</p>
<p>1
5</p>
<p>&lt;
&lt;
&lt;
!
!
M
A
T
H
_
B
L
O
C
K</p>
<div class="math notranslate nohighlight">
\[
\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1,
\]</div>
<p>and so on till the class <span class="math notranslate nohighlight">\(C=K-1\)</span> class</p>
<div class="math notranslate nohighlight">
\[
\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1,
\]</div>
<p>and the model is specified in term of <span class="math notranslate nohighlight">\(K-1\)</span> so-called log-odds or
<strong>logit</strong> transformations.</p>
<p>In our discussion of neural networks we will encounter the above again
in terms of a slightly modified function, the so-called <strong>Softmax</strong> function.</p>
<p>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 <span class="math notranslate nohighlight">\(K\)</span> distinct linear functions,
and the predicted probability for the <span class="math notranslate nohighlight">\(k\)</span>-th class given a sample
vector <span class="math notranslate nohighlight">\(\hat{x}\)</span> and a weighting vector <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> is (with two
predictors):</p>
<div class="math notranslate nohighlight">
\[
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)}}.
\]</div>
<p>It is easy to extend to more predictors. The final class is</p>
<div class="math notranslate nohighlight">
\[
p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}},
\]</div>
<p>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.</p>
<p>To find the optimal parameters we would typically use a gradient
descent method. Newtons method and gradient descent methods are
discussed in the material on <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html">optimization
methods</a>.</p>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='left-prev' id="prev-link" href="chapter3.html" title="previous page"><span class="section-number">2. </span>Linear Regression and more Advanced Regression Analysis</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
@@ -1,236 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Content in Jupyter Book &#8212; My sample book</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Markdown Files" href="markdown.html" />
<link rel="prev" title="Welcome to your Jupyter Book" href="intro.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Welcome to your Jupyter Book
</a>
</li>
</ul>
<ul class="current nav sidenav_l1">
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
Content in Jupyter Book
</a>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="markdown.html">
Markdown Files
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="notebooks.html">
Content with notebooks
</a>
</li>
</ul>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/content.md"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.md</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="content-in-jupyter-book">
<h1>Content in Jupyter Book<a class="headerlink" href="#content-in-jupyter-book" title="Permalink to this headline"></a></h1>
<p>There are many ways to write content in Jupyter Book. This short section
covers a few tips for how to do so.</p>
<div class="toctree-wrapper compound">
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='left-prev' id="prev-link" href="intro.html" title="previous page">Welcome to your Jupyter Book</a>
<a class='right-next' id="next-link" href="markdown.html" title="next page">Markdown Files</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By The Jupyter Book Community<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
+33 -9
View File
@@ -6,7 +6,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index &#8212; My sample book</title>
<title>Index &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
@@ -15,7 +15,8 @@
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
@@ -55,10 +56,10 @@
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<img src="_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
@@ -71,15 +72,25 @@
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Welcome to your Jupyter Book
<a class="reference internal" href="chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="content.html">
Content in Jupyter Book
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
</a>
</li>
</ul>
@@ -123,6 +134,19 @@
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
@@ -167,7 +191,7 @@
<div class="container">
<p>
By The Jupyter Book Community<br/>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
+1 -1
View File
@@ -1,2 +1,2 @@
<meta http-equiv="Refresh" content="0; url=intro.html" />
<meta http-equiv="Refresh" content="0; url=chapter1.html" />
-223
View File
@@ -1,223 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to your Jupyter Book &#8212; My sample book</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Content in Jupyter Book" href="content.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="#">
Welcome to your Jupyter Book
</a>
</li>
</ul>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="content.html">
Content in Jupyter Book
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/intro.md"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.md</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="welcome-to-your-jupyter-book">
<h1>Welcome to your Jupyter Book<a class="headerlink" href="#welcome-to-your-jupyter-book" title="Permalink to this headline"></a></h1>
<p>This is a small sample book to give you a feel for how book content is
structured.</p>
<p>Check out the content pages bundled with this sample book to get started.</p>
<div class="toctree-wrapper compound">
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='right-next' id="next-link" href="content.html" title="next page">Content in Jupyter Book</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By The Jupyter Book Community<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
@@ -1,371 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Files &#8212; My sample book</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Content with notebooks" href="notebooks.html" />
<link rel="prev" title="Content in Jupyter Book" href="content.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Welcome to your Jupyter Book
</a>
</li>
</ul>
<ul class="current nav sidenav_l1">
<li class="toctree-l1 current active">
<a class="reference internal" href="content.html">
Content in Jupyter Book
</a>
<ul class="current">
<li class="toctree-l2 current active">
<a class="current reference internal" href="#">
Markdown Files
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="notebooks.html">
Content with notebooks
</a>
</li>
</ul>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/markdown.md"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.md</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#what-is-myst">
What is MyST?
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#what-are-roles-and-directives">
What are roles and directives?
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#using-a-directive">
Using a directive
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#using-a-role">
Using a role
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#adding-a-citation">
Adding a citation
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#executing-code-in-your-markdown-files">
Executing code in your markdown files
</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="markdown-files">
<h1>Markdown Files<a class="headerlink" href="#markdown-files" title="Permalink to this headline"></a></h1>
<p>Whether you write your books content in Jupyter Notebooks (<code class="docutils literal notranslate"><span class="pre">.ipynb</span></code>) or
in regular markdown files (<code class="docutils literal notranslate"><span class="pre">.md</span></code>), youll write in the same flavor of markdown
called <strong>MyST Markdown</strong>.</p>
<div class="section" id="what-is-myst">
<h2>What is MyST?<a class="headerlink" href="#what-is-myst" title="Permalink to this headline"></a></h2>
<p>MyST stands for “Markedly Structured Text”. It
is a slight variation on a flavor of markdown called “CommonMark” markdown,
with small syntax extensions to allow you to write <strong>roles</strong> and <strong>directives</strong>
in the Sphinx ecosystem.</p>
</div>
<div class="section" id="what-are-roles-and-directives">
<h2>What are roles and directives?<a class="headerlink" href="#what-are-roles-and-directives" title="Permalink to this headline"></a></h2>
<p>Roles and directives are two of the most powerful tools in Jupyter Book. They
are kind of like functions, but written in a markup language. They both
serve a similar purpose, but <strong>roles are written in one line</strong>, whereas
<strong>directives span many lines</strong>. They both accept different kinds of inputs,
and what they do with those inputs depends on the specific role or directive
that is being called.</p>
<div class="section" id="using-a-directive">
<h3>Using a directive<a class="headerlink" href="#using-a-directive" title="Permalink to this headline"></a></h3>
<p>At its simplest, you can insert a directive into your books content like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>```{mydirectivename}
My directive content
```
</pre></div>
</div>
<p>This will only work if a directive with name <code class="docutils literal notranslate"><span class="pre">mydirectivename</span></code> already exists
(which it doesnt). There are many pre-defined directives associated with
Jupyter Book. For example, to insert a note box into your content, you can
use the following directive:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>```{note}
Here is a note
```
</pre></div>
</div>
<p>This results in:</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Here is a note</p>
</div>
<p>In your built book.</p>
<p>For more information on writing directives, see the
<a class="reference external" href="https://myst-parser.readthedocs.io/">MyST documentation</a>.</p>
</div>
<div class="section" id="using-a-role">
<h3>Using a role<a class="headerlink" href="#using-a-role" title="Permalink to this headline"></a></h3>
<p>Roles are very similar to directives, but they are less-complex and written
entirely on one line. You can insert a role into your books content with
this pattern:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>Some content {rolename}`and here is my role&#39;s content!`
</pre></div>
</div>
<p>Again, roles will only work if <code class="docutils literal notranslate"><span class="pre">rolename</span></code> is a valid roles name. For example,
the <code class="docutils literal notranslate"><span class="pre">doc</span></code> role can be used to refer to another page in your book. You can
refer directly to another page by its relative path. For example, the
role syntax <code class="docutils literal notranslate"><span class="pre">{doc}`intro`</span></code> will result in: <a class="reference internal" href="intro.html"><span class="doc">Welcome to your Jupyter Book</span></a>.</p>
<p>For more information on writing roles, see the
<a class="reference external" href="https://myst-parser.readthedocs.io/">MyST documentation</a>.</p>
</div>
<div class="section" id="adding-a-citation">
<h3>Adding a citation<a class="headerlink" href="#adding-a-citation" title="Permalink to this headline"></a></h3>
<p>You can also cite references that are stored in a <code class="docutils literal notranslate"><span class="pre">bibtex</span></code> file. For example,
the following syntax: <code class="docutils literal notranslate"><span class="pre">{cite}`holdgraf_evidence_2014`</span></code> will render like
this: <a class="bibtex reference internal" href="#holdgraf-evidence-2014" id="id1">[HdHPK14]</a>.</p>
<p>Moreoever, you can insert a bibliography into your page with this syntax:
The <code class="docutils literal notranslate"><span class="pre">{bibliography}</span></code> directive must be used for all the <code class="docutils literal notranslate"><span class="pre">{cite}</span></code> roles to
render properly.
For example, if the references for your book are stored in <code class="docutils literal notranslate"><span class="pre">references.bib</span></code>,
then the bibliography is inserted with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>```{bibliography} references.bib
```
</pre></div>
</div>
<p>Resulting in a rendered bibliography that looks like:</p>
<p id="bibtex-bibliography-markdown-0"><dl class="citation">
<dt class="bibtex label" id="holdgraf-evidence-2014"><span class="brackets"><a class="fn-backref" href="#id1">HdHPK14</a></span></dt>
<dd><p>Christopher Ramsay Holdgraf, Wendy de Heer, Brian N. Pasley, and Robert T. Knight. Evidence for Predictive Coding in Human Auditory Cortex. In <em>International Conference on Cognitive Neuroscience</em>. Brisbane, Australia, Australia, 2014. Frontiers in Neuroscience.</p>
</dd>
</dl>
</p>
</div>
<div class="section" id="executing-code-in-your-markdown-files">
<h3>Executing code in your markdown files<a class="headerlink" href="#executing-code-in-your-markdown-files" title="Permalink to this headline"></a></h3>
<p>If youd like to include computational content inside these markdown files,
you can use MyST Markdown to define cells that will be executed when your
book is built. Jupyter Book uses <em>jupytext</em> to do this.</p>
<p>First, add Jupytext metadata to the file. For example, to add Jupytext metadata
to this markdown page, run this command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">jupyter</span><span class="o">-</span><span class="n">book</span> <span class="n">myst</span> <span class="n">init</span> <span class="n">markdown</span><span class="o">.</span><span class="n">md</span>
</pre></div>
</div>
<p>Once a markdown file has Jupytext metadata in it, you can add the following
directive to run the code at build time:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>```{code-cell}
print(&quot;Here is some code to execute&quot;)
```
</pre></div>
</div>
<p>When your book is built, the contents of any <code class="docutils literal notranslate"><span class="pre">{code-cell}</span></code> blocks will be
executed with your default Jupyter kernel, and their outputs will be displayed
in-line with the rest of your content.</p>
<p>For more information about executing computational content with Jupyter Book,
see <a class="reference external" href="https://myst-nb.readthedocs.io/">The MyST-NB documentation</a>.</p>
</div>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='left-prev' id="prev-link" href="content.html" title="previous page">Content in Jupyter Book</a>
<a class='right-next' id="next-link" href="notebooks.html" title="next page">Content with notebooks</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By The Jupyter Book Community<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
@@ -1,340 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Content with notebooks &#8212; My sample book</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="prev" title="Markdown Files" href="markdown.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Welcome to your Jupyter Book
</a>
</li>
</ul>
<ul class="current nav sidenav_l1">
<li class="toctree-l1 current active">
<a class="reference internal" href="content.html">
Content in Jupyter Book
</a>
<ul class="current">
<li class="toctree-l2">
<a class="reference internal" href="markdown.html">
Markdown Files
</a>
</li>
<li class="toctree-l2 current active">
<a class="current reference internal" href="#">
Content with notebooks
</a>
</li>
</ul>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/notebooks.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Launch interactive content"><i class="fas fa-rocket"></i></button>
<div class="dropdown-buttons">
<a class="binder-button" href="https://mybinder.org/v2/gh/executablebooks/jupyter-book/master?urlpath=tree/notebooks.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Launch Binder" data-toggle="tooltip"
data-placement="left"><img class="binder-button-logo"
src="_static/images/logo_binder.svg"
alt="Interact on binder">Binder</button></a>
<a class="colab-button" href="https://colab.research.google.com/github/executablebooks/jupyter-book/blob/master/notebooks.ipynb"><button type="button" class="btn btn-secondary topbarbtn"
title="Launch Colab" data-toggle="tooltip" data-placement="left"><img class="colab-button-logo"
src="_static/images/logo_colab.png"
alt="Interact on Colab">Colab</button></a>
</div>
</div>
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#markdown-notebooks">
Markdown + notebooks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#myst-markdown">
MyST markdown
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#code-blocks-and-outputs">
Code blocks and outputs
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="content-with-notebooks">
<h1>Content with notebooks<a class="headerlink" href="#content-with-notebooks" title="Permalink to this headline"></a></h1>
<p>You can also create content with Jupyter Notebooks. This means that you can include
code blocks and their outputs in your book.</p>
<div class="section" id="markdown-notebooks">
<h2>Markdown + notebooks<a class="headerlink" href="#markdown-notebooks" title="Permalink to this headline"></a></h2>
<p>As it is markdown, you can embed images, HTML, etc into your posts!</p>
<p><img alt="" src="https://myst-parser.readthedocs.io/en/latest/_static/logo.png" /></p>
<p>You an also <span class="math notranslate nohighlight">\(add_{math}\)</span> and</p>
<div class="math notranslate nohighlight">
\[
math^{blocks}
\]</div>
<p>or</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{aligned}
\mbox{mean} la_{tex} \\ \\
math blocks
\end{aligned}
\end{split}\]</div>
<p>But make sure you $Escape $your $dollar signs $you want to keep!</p>
</div>
<div class="section" id="myst-markdown">
<h2>MyST markdown<a class="headerlink" href="#myst-markdown" title="Permalink to this headline"></a></h2>
<p>MyST markdown works in Jupyter Notebooks as well. For more information about MyST markdown, check
out <a class="reference external" href="https://jupyterbook.org/content/myst.html">the MyST guide in Jupyter Book</a>,
or see <a class="reference external" href="https://myst-parser.readthedocs.io/en/latest/">the MyST markdown documentation</a>.</p>
</div>
<div class="section" id="code-blocks-and-outputs">
<h2>Code blocks and outputs<a class="headerlink" href="#code-blocks-and-outputs" title="Permalink to this headline"></a></h2>
<p>Jupyter Book will also embed your code blocks and output in your book.
For example, heres some sample Matplotlib code:</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">rcParams</span><span class="p">,</span> <span class="n">cycler</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ion</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Fixing random state for reproducibility</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">19680801</span><span class="p">)</span>
<span class="n">N</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">logspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span> <span class="o">+</span> <span class="n">ii</span> <span class="k">for</span> <span class="n">ii</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">)]</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="o">.</span><span class="n">T</span>
<span class="n">cmap</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">cm</span><span class="o">.</span><span class="n">coolwarm</span>
<span class="n">rcParams</span><span class="p">[</span><span class="s1">&#39;axes.prop_cycle&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">cycler</span><span class="p">(</span><span class="n">color</span><span class="o">=</span><span class="n">cmap</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">N</span><span class="p">)))</span>
<span class="kn">from</span> <span class="nn">matplotlib.lines</span> <span class="kn">import</span> <span class="n">Line2D</span>
<span class="n">custom_lines</span> <span class="o">=</span> <span class="p">[</span><span class="n">Line2D</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">color</span><span class="o">=</span><span class="n">cmap</span><span class="p">(</span><span class="mf">0.</span><span class="p">),</span> <span class="n">lw</span><span class="o">=</span><span class="mi">4</span><span class="p">),</span>
<span class="n">Line2D</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">color</span><span class="o">=</span><span class="n">cmap</span><span class="p">(</span><span class="o">.</span><span class="mi">5</span><span class="p">),</span> <span class="n">lw</span><span class="o">=</span><span class="mi">4</span><span class="p">),</span>
<span class="n">Line2D</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">color</span><span class="o">=</span><span class="n">cmap</span><span class="p">(</span><span class="mf">1.</span><span class="p">),</span> <span class="n">lw</span><span class="o">=</span><span class="mi">4</span><span class="p">)]</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<span class="n">lines</span> <span class="o">=</span> <span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">custom_lines</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cold&#39;</span><span class="p">,</span> <span class="s1">&#39;Medium&#39;</span><span class="p">,</span> <span class="s1">&#39;Hot&#39;</span><span class="p">]);</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/notebooks_2_0.png" src="_images/notebooks_2_0.png" />
</div>
</div>
<p>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 <a class="reference external" href="https://jupyterbook.org">the Jupyter Book documentation</a></p>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='left-prev' id="prev-link" href="markdown.html" title="previous page">Markdown Files</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By The Jupyter Book Community<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
Binary file not shown.
@@ -17,42 +17,15 @@ Traceback (most recent call last):
raise CellExecutionError.from_cell_and_msg(cell, exec_reply['content'])
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
# Blocking
@timeFunction
def blocking(self, blockSizeMax = 500):
blockSizeMin = 1
self.blockSizes = []
self.meanVec = []
self.varVec = []
for i in range(blockSizeMin, blockSizeMax):
if(len(self.data) % i != 0):
pass#continue
blockSize = i
meanTempVec = []
varTempVec = []
startPoint = 0
endPoint = blockSize
while endPoint <= len(self.data):
meanTempVec.append(np.average(self.data[startPoint:endPoint]))
startPoint = endPoint
endPoint += blockSize
mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
self.meanVec.append(mean)
self.varVec.append(var)
self.blockSizes.append(blockSize)
self.blockingAvg = np.average(self.meanVec[-200:])
self.blockingVar = (np.average(self.varVec[-200:]))
self.blockingStd = np.sqrt(self.blockingVar)
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
------------------
 File "<ipython-input-6-2ff97f4bf03b>", line 2
 @timeFunction
 File "<ipython-input-7-f6d7a289d493>", line 3
 print(x)
 ^
IndentationError: unexpected indent
SyntaxError: invalid syntax
IndentationError: unexpected indent (<ipython-input-6-2ff97f4bf03b>, line 2)
SyntaxError: invalid syntax (<ipython-input-7-f6d7a289d493>, line 3)
+33 -9
View File
@@ -6,7 +6,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search &#8212; My sample book</title>
<title>Search &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
@@ -15,7 +15,8 @@
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-dropdown.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
@@ -60,10 +61,10 @@
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/logo.png" class="logo" alt="logo">
<img src="_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">My sample book</h1>
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
@@ -76,15 +77,25 @@
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Welcome to your Jupyter Book
<a class="reference internal" href="chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="content.html">
Content in Jupyter Book
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
</a>
</li>
</ul>
@@ -128,6 +139,19 @@
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
@@ -186,7 +210,7 @@
<div class="container">
<p>
By The Jupyter Book Community<br/>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
File diff suppressed because one or more lines are too long
@@ -4,21 +4,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Introduction to Applied Data Analysis and Machine Learning -->\n",
"# Introduction to Applied Data Analysis and Machine Learning\n",
"<!-- 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 -->\n",
"<!-- 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: **Sep 19, 2020**\n",
"\n",
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Introduction\n",
"\n",
"During the last two decades there has been a swift and amazing\n",
"development of Machine Learning techniques and algorithms that impact\n",
@@ -167,8 +153,6 @@
"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",
@@ -184,8 +168,6 @@
"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",
@@ -196,12 +178,6 @@
"of the algorithms and methods we will discuss.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Types of Machine Learning\n",
"\n",
"\n",
"The approaches to machine learning are many, but are often split into\n",
"two main categories. In *supervised learning* we know the answer to a\n",
"problem, and let the computer deduce the logic behind it. On the other\n",
@@ -221,27 +197,15 @@
"\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.\n",
"\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 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",
"* 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",
"\n",
"\n",
"\n",
"\n",
"\n",
"## An optimization/minimization problem\n",
"\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",
@@ -297,10 +261,6 @@
"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",
@@ -445,12 +405,11 @@
"```{toctree}\n",
":hidden:\n",
":titlesonly:\n",
"\n",
":numbered: \n",
"\n",
"chapter2\n",
"chapter3\n",
"chapter4\n",
"chapter5\n",
"```\n"
]
}
@@ -1,18 +1,4 @@
<!-- dom:TITLE: Introduction to Applied Data Analysis and Machine Learning -->
# Introduction to Applied Data Analysis and Machine Learning
<!-- 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: **Sep 19, 2020**
Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
## Introduction
During the last two decades there has been a swift and amazing
development of Machine Learning techniques and algorithms that impact
@@ -161,8 +147,6 @@ 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
@@ -178,8 +162,6 @@ 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
@@ -190,12 +172,6 @@ Carlo methods are central elements in a proper understanding of many
of the algorithms and methods we will discuss.
## Types of Machine Learning
The approaches to machine learning are many, but are often split into
two main categories. In *supervised learning* we know the answer to a
problem, and let the computer deduce the logic behind it. On the other
@@ -215,27 +191,15 @@ desired output of a system. Some of the most common tasks are:
* 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, 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 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.
* 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.
## An optimization/minimization problem
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**.
@@ -291,10 +255,6 @@ 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
@@ -434,10 +394,9 @@ society.
```{toctree}
:hidden:
:titlesonly:
:numbered:
chapter2
chapter3
chapter4
chapter5
```
File diff suppressed because one or more lines are too long
@@ -1,17 +1,4 @@
<!-- dom:TITLE: Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters -->
# Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters
<!-- 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: **Dec 25, 2019**
Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
# Getting started, our first data and Machine Learning encounters
## Introduction
@@ -395,7 +382,6 @@ Here follows a simple example where we set up an array of ten elements, all dete
n = 10
x = np.random.normal(size=n)
print(x)
print(x[1])
We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.
Another alternative is to declare a vector as follows
@@ -436,13 +422,13 @@ print(x)
or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
x = np.log(np.array([4.0, 7.0, 8.0])
print(x.itemsize)
## Matrices in Python
@@ -482,7 +468,7 @@ or initializing all elements to
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.eye( n )
A = np.ones( (n, n) )
print(A)
or as unitarily distributed random numbers (see the material on random number generators in the statistics part)
@@ -628,8 +614,6 @@ display(df)
print(df.mean())
print(df.std())
display(df**2)
print(df-df.mean())
Thereafter we can select specific columns only and plot final results
@@ -755,14 +739,13 @@ import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
x = np.random.rand(100,1)
y = 2*x+0.01*np.random.randn(100,1)
y = 2*x+np.random.randn(100,1)
linreg = LinearRegression()
linreg.fit(x,y)
#ynew = linreg.predict(x)
#xnew = np.array([[0],[1]])
ypredict = linreg.predict(x)
xnew = np.array([[0],[1]])
ypredict = linreg.predict(xnew)
plt.plot(x, ypredict, "r-")
plt.plot(xnew, ypredict, "r-")
plt.plot(x, y ,'ro')
plt.axis([0,1.0,0, 5.0])
plt.xlabel(r'$x$')
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

File diff suppressed because one or more lines are too long
@@ -1,544 +0,0 @@
<!-- 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')
Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

File diff suppressed because one or more lines are too long
@@ -1,544 +0,0 @@
<!-- 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')
Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Some files were not shown because too many files have changed in this diff Show More