diff --git a/doc/Projects/2020/Project1/html/._Project1-bs000.html b/doc/Projects/2020/Project1/html/._Project1-bs000.html
index d635d38c9..2028b3e80 100644
--- a/doc/Projects/2020/Project1/html/._Project1-bs000.html
+++ b/doc/Projects/2020/Project1/html/._Project1-bs000.html
@@ -165,7 +165,7 @@ MathJax.Hub.Config({
Department of Physics, University of Oslo, Norway
-
Sep 7, 2020
+Sep 16, 2020
@@ -404,18 +404,16 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
+data.
Implement the \( k \)-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
Scikit-Learn if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code.
+Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code. Comment your results. Try \( 5-10 \) folds.
You can also compare your own cross-validation code with the one provided by Scikit-Learn.
Part d): Ridge Regression on the Franke function with resampling
diff --git a/doc/Projects/2020/Project1/html/Project1-bs.html b/doc/Projects/2020/Project1/html/Project1-bs.html
index d635d38c9..2028b3e80 100644
--- a/doc/Projects/2020/Project1/html/Project1-bs.html
+++ b/doc/Projects/2020/Project1/html/Project1-bs.html
@@ -165,7 +165,7 @@ MathJax.Hub.Config({
Department of Physics, University of Oslo, Norway
-
Sep 7, 2020
+Sep 16, 2020
@@ -404,18 +404,16 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
+data.
Implement the \( k \)-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
Scikit-Learn if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code.
+Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code. Comment your results. Try \( 5-10 \) folds.
You can also compare your own cross-validation code with the one provided by Scikit-Learn.
Part d): Ridge Regression on the Franke function with resampling
diff --git a/doc/Projects/2020/Project1/html/Project1.html b/doc/Projects/2020/Project1/html/Project1.html
index fee6e0ce3..e92e775bc 100644
--- a/doc/Projects/2020/Project1/html/Project1.html
+++ b/doc/Projects/2020/Project1/html/Project1.html
@@ -122,7 +122,7 @@ MathJax.Hub.Config({
Department of Physics, University of Oslo, Norway
-
Sep 7, 2020
+Sep 16, 2020
Regression analysis and resampling methods
@@ -359,18 +359,16 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
+data.
Implement the \( k \)-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
Scikit-Learn if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code.
+Compare the MSE you get from your cross-validation code with the one you got from your bootstrap code. Comment your results. Try \( 5-10 \) folds.
You can also compare your own cross-validation code with the one provided by Scikit-Learn.
Part d): Ridge Regression on the Franke function with resampling
diff --git a/doc/Projects/2020/Project1/ipynb/Project1.ipynb b/doc/Projects/2020/Project1/ipynb/Project1.ipynb
index f3707da16..db0f42274 100644
--- a/doc/Projects/2020/Project1/ipynb/Project1.ipynb
+++ b/doc/Projects/2020/Project1/ipynb/Project1.ipynb
@@ -10,7 +10,7 @@
" \n",
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n",
"\n",
- "Date: **Sep 7, 2020**\n",
+ "Date: **Sep 16, 2020**\n",
"\n",
"Copyright 1999-2020, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -318,19 +318,15 @@
"The aim here is to write your own code for another widely popular\n",
"resampling technique, the so-called cross-validation method. Again,\n",
"before you start with cross-validation approach, you should scale your\n",
- "data and split it in test and training data as you did earlier.\n",
- "Perform a resampling of the data where you split the data in training\n",
- "data and test data using for example\n",
- "\n",
- "\n",
+ "data.\n",
"\n",
"Implement the $k$-fold cross-validation algorithm (write your own\n",
"code) and evaluate again the MSE function resulting\n",
- "from the test data. You can compare your own code with that from\n",
+ "from the test folds. You can compare your own code with that from\n",
"**Scikit-Learn** if needed. \n",
"\n",
- "Compare the MSE you get from your cross-validation code with the one you got from your **bootstrap** code.\n",
- "You can also compare your own cross-validation code with the one provided by **Scikit-Learn**.\n",
+ "Compare the MSE you get from your cross-validation code with the one you got from your **bootstrap** code. Comment your results. Try $5-10$ folds. \n",
+ "You can also compare your own cross-validation code with the one provided by **Scikit-Learn**. \n",
"\n",
"\n",
"### Part d): Ridge Regression on the Franke function with resampling\n",
diff --git a/doc/Projects/2020/Project1/ipynb/ipynb-Project1-src.tar.gz b/doc/Projects/2020/Project1/ipynb/ipynb-Project1-src.tar.gz
index f6272831b..b38221a76 100644
Binary files a/doc/Projects/2020/Project1/ipynb/ipynb-Project1-src.tar.gz and b/doc/Projects/2020/Project1/ipynb/ipynb-Project1-src.tar.gz differ
diff --git a/doc/Projects/2020/Project1/pdf/Project1.aux b/doc/Projects/2020/Project1/pdf/Project1.aux
new file mode 100644
index 000000000..c3481b2c3
--- /dev/null
+++ b/doc/Projects/2020/Project1/pdf/Project1.aux
@@ -0,0 +1,25 @@
+\relax
+\providecommand\hyper@newdestlabel[2]{}
+\providecommand\HyperFirstAtBeginDocument{\AtBeginDocument}
+\HyperFirstAtBeginDocument{\ifx\hyper@anchor\@undefined
+\global\let\oldcontentsline\contentsline
+\gdef\contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}}
+\global\let\oldnewlabel\newlabel
+\gdef\newlabel#1#2{\newlabelxx{#1}#2}
+\gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}}
+\AtEndDocument{\ifx\hyper@anchor\@undefined
+\let\contentsline\oldcontentsline
+\let\newlabel\oldnewlabel
+\fi}
+\fi}
+\global\let\hyper@last\relax
+\gdef\HyperFirstAtBeginDocument#1{#1}
+\providecommand\HyField@AuxAddToFields[1]{}
+\providecommand\HyField@AuxAddToCoFields[2]{}
+\@writefile{toc}{\contentsline {paragraph}{Part a): Ordinary Least Square (OLS) on the Franke function.}{3}{section*.2}}
+\@writefile{toc}{\contentsline {paragraph}{Part b): Bias-variance trade-off and resamplng techniques.}{4}{section*.3}}
+\@writefile{toc}{\contentsline {paragraph}{Part c) Cross-validation as resampling techniques, adding more complexity.}{5}{section*.4}}
+\@writefile{toc}{\contentsline {paragraph}{Part d): Ridge Regression on the Franke function with resampling.}{5}{section*.5}}
+\@writefile{toc}{\contentsline {paragraph}{Part e): Lasso Regression on the Franke function with resampling.}{5}{section*.6}}
+\@writefile{toc}{\contentsline {paragraph}{Part f): Introducing real data and preparing the data analysis.}{5}{section*.7}}
+\@writefile{toc}{\contentsline {paragraph}{Part g) OLS, Ridge and Lasso regression with resampling.}{6}{section*.8}}
diff --git a/doc/Projects/2020/Project1/pdf/Project1.idx b/doc/Projects/2020/Project1/pdf/Project1.idx
new file mode 100644
index 000000000..e69de29bb
diff --git a/doc/Projects/2020/Project1/pdf/Project1.log b/doc/Projects/2020/Project1/pdf/Project1.log
new file mode 100644
index 000000000..bc230bb1c
--- /dev/null
+++ b/doc/Projects/2020/Project1/pdf/Project1.log
@@ -0,0 +1,851 @@
+This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=pdflatex 2018.10.20) 16 SEP 2020 17:14
+entering extended mode
+ restricted \write18 enabled.
+ %&-line parsing enabled.
+**Project1
+(./Project1.tex
+LaTeX2e <2016/02/01>
+Babel <3.9q> and hyphenation patterns for 81 language(s) loaded.
+(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
+Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
+(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo
+File: size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option)
+)
+\c@part=\count79
+\c@section=\count80
+\c@subsection=\count81
+\c@subsubsection=\count82
+\c@paragraph=\count83
+\c@subparagraph=\count84
+\c@figure=\count85
+\c@table=\count86
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+)
+(/usr/share/texlive/texmf-dist/tex/latex/relsize/relsize.sty
+Package: relsize 2013/03/29 ver 4.1
+)
+(/usr/share/texlive/texmf-dist/tex/latex/base/makeidx.sty
+Package: makeidx 2014/09/29 v1.0m Standard LaTeX package
+)
+(/usr/share/texlive/texmf-dist/tex/latex/graphics/color.sty
+Package: color 2016/01/03 v1.1b Standard LaTeX Color (DPC)
+
+(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/color.cfg
+File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
+)
+Package color Info: Driver file: pdftex.def on input line 143.
+
+(/usr/share/texlive/texmf-dist/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX
+
+(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/infwarerr.sty
+Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO)
+)
+(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ltxcmds.sty
+Package: ltxcmds 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
+)
+\Gread@gobject=\count87
+))
+(/usr/share/texlive/texmf-dist/tex/latex/setspace/setspace.sty
+Package: setspace 2011/12/19 v6.7a set line spacing
+)
+(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2016/03/03 v2.15a AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01 AMS text
+
+(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0 generic functions
+\@emptytoks=\toks14
+\ex@=\dimen103
+))
+(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d Bold Symbols
+\pmbraise@=\dimen104
+)
+(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf@bad=\count88
+LaTeX Info: Redefining \frac on input line 199.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 297.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 394.
+LaTeX Info: Redefining \dots on input line 397.
+LaTeX Info: Redefining \cdots on input line 518.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big@size=\dimen105
+LaTeX Font Info: Redeclaring font encoding OML on input line 630.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 631.
+\macc@depth=\count93
+\c@MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c@parentequation=\count95
+\dspbrk@lvl=\count96
+\tag@help=\toks15
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks16
+\eqnshift@=\dimen106
+\alignsep@=\dimen107
+\tagshift@=\dimen108
+\tagwidth@=\dimen109
+\totwidth@=\dimen110
+\lineht@=\dimen111
+\@envbody=\toks17
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay@stack=\toks18
+LaTeX Info: Redefining \[ on input line 2735.
+LaTeX Info: Redefining \] on input line 2736.
+)
+(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty
+Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support
+\symAMSa=\mathgroup4
+\symAMSb=\mathgroup5
+LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold'
+(Font) U/euf/m/n --> U/euf/b/n on input line 106.
+)
+(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty
+Package: amssymb 2013/01/14 v3.01 AMS font symbols
+)
+(/usr/share/texlive/texmf-dist/tex/latex/xcolor/xcolor.sty
+Package: xcolor 2007/01/21 v2.11 LaTeX color extensions (UK)
+
+(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/color.cfg
+File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
+)
+Package xcolor Info: Driver file: pdftex.def on input line 225.
+
+(/usr/share/texlive/texmf-dist/tex/latex/colortbl/colortbl.sty
+Package: colortbl 2012/02/13 v1.0a Color table columns (DPC)
+
+(/usr/share/texlive/texmf-dist/tex/latex/tools/array.sty
+Package: array 2014/10/28 v2.4c Tabular extension package (FMi)
+\col@sep=\dimen112
+\extrarowheight=\dimen113
+\NC@list=\toks19
+\extratabsurround=\skip46
+\backup@length=\skip47
+)
+\everycr=\toks20
+\minrowclearance=\skip48
+)
+LaTeX Info: Redefining \color on input line 702.
+\rownum=\count100
+Package xcolor Info: Model `cmy' substituted by `cmy0' on input line 1337.
+Package xcolor Info: Model `hsb' substituted by `rgb' on input line 1341.
+Package xcolor Info: Model `RGB' extended on input line 1353.
+Package xcolor Info: Model `HTML' substituted by `rgb' on input line 1355.
+Package xcolor Info: Model `Hsb' substituted by `hsb' on input line 1356.
+Package xcolor Info: Model `tHsb' substituted by `hsb' on input line 1357.
+Package xcolor Info: Model `HSB' substituted by `hsb' on input line 1358.
+Package xcolor Info: Model `Gray' substituted by `gray' on input line 1359.
+Package xcolor Info: Model `wave' substituted by `hsb' on input line 1360.
+)
+(/usr/share/texlive/texmf-dist/tex/latex/tools/bm.sty
+Package: bm 2014/10/28 v1.1c Bold Symbol Support (DPC/FMi)
+\symboldoperators=\mathgroup6
+\symboldletters=\mathgroup7
+\symboldsymbols=\mathgroup8
+LaTeX Font Info: Redeclaring math alphabet \mathbf on input line 141.
+LaTeX Info: Redefining \bm on input line 207.
+)
+(/usr/share/texlive/texmf-dist/tex/latex/ltablex/ltablex.sty
+Package: ltablex 2014/08/13 v1.1 Modified tabularx
+
+(/usr/share/texlive/texmf-dist/tex/latex/tools/longtable.sty
+Package: longtable 2014/10/28 v4.11 Multi-page Table package (DPC)
+\LTleft=\skip49
+\LTright=\skip50
+\LTpre=\skip51
+\LTpost=\skip52
+\LTchunksize=\count101
+\LTcapwidth=\dimen114
+\LT@head=\box28
+\LT@firsthead=\box29
+\LT@foot=\box30
+\LT@lastfoot=\box31
+\LT@cols=\count102
+\LT@rows=\count103
+\c@LT@tables=\count104
+\c@LT@chunks=\count105
+\LT@p@ftn=\toks21
+)
+(/usr/share/texlive/texmf-dist/tex/latex/tools/tabularx.sty
+Package: tabularx 2014/10/28 v2.10 `tabularx' package (DPC)
+\TX@col@width=\dimen115
+\TX@old@table=\dimen116
+\TX@old@col=\dimen117
+\TX@target=\dimen118
+\TX@delta=\dimen119
+\TX@cols=\count106
+\TX@ftn=\toks22
+))
+(/usr/share/texlive/texmf-dist/tex/latex/microtype/microtype.sty
+Package: microtype 2013/05/23 v2.5a Micro-typographical refinements (RS)
+
+(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty
+Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
+\KV@toks@=\toks23
+)
+\MT@toks=\toks24
+\MT@count=\count107
+LaTeX Info: Redefining \textls on input line 766.
+\MT@outer@kern=\dimen120
+LaTeX Info: Redefining \textmicrotypecontext on input line 1285.
+\MT@listname@count=\count108
+
+(/usr/share/texlive/texmf-dist/tex/latex/microtype/microtype-pdftex.def
+File: microtype-pdftex.def 2013/05/23 v2.5a Definitions specific to pdftex (RS)
+
+LaTeX Info: Redefining \lsstyle on input line 915.
+LaTeX Info: Redefining \lslig on input line 915.
+\MT@outer@space=\skip53
+)
+Package microtype Info: Loading configuration file microtype.cfg.
+
+(/usr/share/texlive/texmf-dist/tex/latex/microtype/microtype.cfg
+File: microtype.cfg 2013/05/23 v2.5a microtype main configuration file (RS)
+))
+(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
+Package: graphicx 2014/10/28 v1.0g Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
+Package: graphics 2016/01/03 v1.0q Standard LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty
+Package: trig 2016/01/03 v1.10 sin cos tan (DPC)
+)
+(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg
+File: graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
+)
+Package graphics Info: Driver file: pdftex.def on input line 95.
+)
+\Gin@req@height=\dimen121
+\Gin@req@width=\dimen122
+)
+(/usr/share/texlive/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty
+Package: fancyvrb 2008/02/07
+
+Style option: `fancyvrb' v2.7a, with DG/SPQR fixes, and firstline=lastline fix
+<2008/02/07> (tvz)
+\FV@CodeLineNo=\count109
+\FV@InFile=\read1
+\FV@TabBox=\box32
+\c@FancyVerbLine=\count110
+\FV@StepNumber=\count111
+\FV@OutFile=\write3
+) (/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty
+Package: fontenc 2005/09/27 v1.99g Standard LaTeX package
+
+(/usr/share/texlive/texmf-dist/tex/latex/base/t1enc.def
+File: t1enc.def 2005/09/27 v1.99g Standard LaTeX file
+LaTeX Font Info: Redeclaring font encoding T1 on input line 48.
+))
+(/usr/share/texlive/texmf-dist/tex/latex/ucs/ucs.sty
+Package: ucs 2013/05/11 v2.2 UCS: Unicode input support
+
+(/usr/share/texlive/texmf-dist/tex/latex/ucs/data/uni-global.def
+File: uni-global.def 2013/05/13 UCS: Unicode global data
+)
+\uc@secondtry=\count112
+\uc@combtoks=\toks25
+\uc@combtoksb=\toks26
+\uc@temptokena=\toks27
+)
+(/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty
+Package: inputenc 2015/03/17 v1.2c Input encoding file
+\inpenc@prehook=\toks28
+\inpenc@posthook=\toks29
+
+(/usr/share/texlive/texmf-dist/tex/latex/ucs/utf8x.def
+File: utf8x.def 2004/10/17 UCS: Input encoding UTF-8
+))
+(/usr/share/texmf/tex/latex/lm/lmodern.sty
+Package: lmodern 2009/10/30 v1.6 Latin Modern Fonts
+LaTeX Font Info: Overwriting symbol font `operators' in version `normal'
+(Font) OT1/cmr/m/n --> OT1/lmr/m/n on input line 22.
+LaTeX Font Info: Overwriting symbol font `letters' in version `normal'
+(Font) OML/cmm/m/it --> OML/lmm/m/it on input line 23.
+LaTeX Font Info: Overwriting symbol font `symbols' in version `normal'
+(Font) OMS/cmsy/m/n --> OMS/lmsy/m/n on input line 24.
+LaTeX Font Info: Overwriting symbol font `largesymbols' in version `normal'
+(Font) OMX/cmex/m/n --> OMX/lmex/m/n on input line 25.
+LaTeX Font Info: Overwriting symbol font `operators' in version `bold'
+(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 26.
+LaTeX Font Info: Overwriting symbol font `letters' in version `bold'
+(Font) OML/cmm/b/it --> OML/lmm/b/it on input line 27.
+LaTeX Font Info: Overwriting symbol font `symbols' in version `bold'
+(Font) OMS/cmsy/b/n --> OMS/lmsy/b/n on input line 28.
+LaTeX Font Info: Overwriting symbol font `largesymbols' in version `bold'
+(Font) OMX/cmex/m/n --> OMX/lmex/m/n on input line 29.
+LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `normal'
+(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 31.
+LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `normal'
+(Font) OT1/cmss/m/n --> OT1/lmss/m/n on input line 32.
+LaTeX Font Info: Overwriting math alphabet `\mathit' in version `normal'
+(Font) OT1/cmr/m/it --> OT1/lmr/m/it on input line 33.
+LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `normal'
+(Font) OT1/cmtt/m/n --> OT1/lmtt/m/n on input line 34.
+LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `bold'
+(Font) OT1/cmr/bx/n --> OT1/lmr/bx/n on input line 35.
+LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold'
+(Font) OT1/cmss/bx/n --> OT1/lmss/bx/n on input line 36.
+LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold'
+(Font) OT1/cmr/bx/it --> OT1/lmr/bx/it on input line 37.
+LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `bold'
+(Font) OT1/cmtt/m/n --> OT1/lmtt/m/n on input line 38.
+)
+(/usr/share/texlive/texmf-dist/tex/latex/hyperref/hyperref.sty
+Package: hyperref 2012/11/06 v6.83m Hypertext links for LaTeX
+
+(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/hobsub-hyperref.sty
+Package: hobsub-hyperref 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO)
+
+
+(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/hobsub-generic.sty
+Package: hobsub-generic 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO)
+Package: hobsub 2012/05/28 v1.13 Construct package bundles (HO)
+Package hobsub Info: Skipping package `infwarerr' (already loaded).
+Package hobsub Info: Skipping package `ltxcmds' (already loaded).
+Package: ifluatex 2010/03/01 v1.3 Provides the ifluatex switch (HO)
+Package ifluatex Info: LuaTeX not detected.
+Package: ifvtex 2010/03/01 v1.5 Detect VTeX and its facilities (HO)
+Package ifvtex Info: VTeX not detected.
+Package: intcalc 2007/09/27 v1.1 Expandable calculations with integers (HO)
+Package: ifpdf 2011/01/30 v2.3 Provides the ifpdf switch (HO)
+Package ifpdf Info: pdfTeX in PDF mode is detected.
+Package: etexcmds 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
+Package etexcmds Info: Could not find \expanded.
+(etexcmds) That can mean that you are not using pdfTeX 1.50 or
+(etexcmds) that some package has redefined \expanded.
+(etexcmds) In the latter case, load this package earlier.
+Package: kvsetkeys 2012/04/25 v1.16 Key value parser (HO)
+Package: kvdefinekeys 2011/04/07 v1.3 Define keys (HO)
+Package: pdftexcmds 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO
+)
+Package pdftexcmds Info: LuaTeX not detected.
+Package pdftexcmds Info: \pdf@primitive is available.
+Package pdftexcmds Info: \pdf@ifprimitive is available.
+Package pdftexcmds Info: \pdfdraftmode found.
+Package: pdfescape 2011/11/25 v1.13 Implements pdfTeX's escape features (HO)
+Package: bigintcalc 2012/04/08 v1.3 Expandable calculations on big integers (HO
+)
+Package: bitset 2011/01/30 v1.1 Handle bit-vector datatype (HO)
+Package: uniquecounter 2011/01/30 v1.2 Provide unlimited unique counter (HO)
+)
+Package hobsub Info: Skipping package `hobsub' (already loaded).
+Package: letltxmacro 2010/09/02 v1.4 Let assignment for LaTeX macros (HO)
+Package: hopatch 2012/05/28 v1.2 Wrapper for package hooks (HO)
+Package: xcolor-patch 2011/01/30 xcolor patch
+Package: atveryend 2011/06/30 v1.8 Hooks at the very end of document (HO)
+Package atveryend Info: \enddocument detected (standard20110627).
+Package: atbegshi 2011/10/05 v1.16 At begin shipout hook (HO)
+Package: refcount 2011/10/16 v3.4 Data extraction from label references (HO)
+Package: hycolor 2011/01/30 v1.7 Color options for hyperref/bookmark (HO)
+)
+(/usr/share/texlive/texmf-dist/tex/generic/ifxetex/ifxetex.sty
+Package: ifxetex 2010/09/12 v0.6 Provides ifxetex conditional
+)
+(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/auxhook.sty
+Package: auxhook 2011/03/04 v1.3 Hooks for auxiliary files (HO)
+)
+(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/kvoptions.sty
+Package: kvoptions 2011/06/30 v3.11 Key value format for package options (HO)
+)
+\@linkdim=\dimen123
+\Hy@linkcounter=\count113
+\Hy@pagecounter=\count114
+
+(/usr/share/texlive/texmf-dist/tex/latex/hyperref/pd1enc.def
+File: pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO)
+)
+\Hy@SavedSpaceFactor=\count115
+
+(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/hyperref.cfg
+File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive
+)
+Package hyperref Info: Option `final' set `true' on input line 4319.
+Package hyperref Info: Hyper figures OFF on input line 4443.
+Package hyperref Info: Link nesting OFF on input line 4448.
+Package hyperref Info: Hyper index ON on input line 4451.
+Package hyperref Info: Plain pages OFF on input line 4458.
+Package hyperref Info: Backreferencing OFF on input line 4463.
+Package hyperref Info: Implicit mode ON; LaTeX internals redefined.
+Package hyperref Info: Bookmarks ON on input line 4688.
+\c@Hy@tempcnt=\count116
+
+(/usr/share/texlive/texmf-dist/tex/latex/url/url.sty
+\Urlmuskip=\muskip11
+Package: url 2013/09/16 ver 3.4 Verb mode for urls, etc.
+)
+LaTeX Info: Redefining \url on input line 5041.
+\XeTeXLinkMargin=\dimen124
+\Fld@menulength=\count117
+\Field@Width=\dimen125
+\Fld@charsize=\dimen126
+Package hyperref Info: Hyper figures OFF on input line 6295.
+Package hyperref Info: Link nesting OFF on input line 6300.
+Package hyperref Info: Hyper index ON on input line 6303.
+Package hyperref Info: backreferencing OFF on input line 6310.
+Package hyperref Info: Link coloring OFF on input line 6315.
+Package hyperref Info: Link coloring with OCG OFF on input line 6320.
+Package hyperref Info: PDF/A mode OFF on input line 6325.
+LaTeX Info: Redefining \ref on input line 6365.
+LaTeX Info: Redefining \pageref on input line 6369.
+\Hy@abspage=\count118
+\c@Item=\count119
+\c@Hfootnote=\count120
+)
+
+Package hyperref Message: Driver (autodetected): hpdftex.
+
+(/usr/share/texlive/texmf-dist/tex/latex/hyperref/hpdftex.def
+File: hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX
+\Fld@listcount=\count121
+\c@bookmark@seq@number=\count122
+
+(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/rerunfilecheck.sty
+Package: rerunfilecheck 2011/04/15 v1.7 Rerun checks for auxiliary files (HO)
+Package uniquecounter Info: New unique counter `rerunfilecheck' on input line 2
+82.
+)
+\Hy@SectionHShift=\skip54
+)
+Package hyperref Info: Option `breaklinks' set `true' on input line 46.
+Package hyperref Info: Option `colorlinks' set `true' on input line 46.
+Package hyperref Info: Option `pdfmenubar' set `true' on input line 46.
+Package hyperref Info: Option `pdftoolbar' set `true' on input line 46.
+
+(/usr/share/texlive/texmf-dist/tex/latex/fancyhdr/fancyhdr.sty
+\fancy@headwidth=\skip55
+\f@ncyO@elh=\skip56
+\f@ncyO@erh=\skip57
+\f@ncyO@olh=\skip58
+\f@ncyO@orh=\skip59
+\f@ncyO@elf=\skip60
+\f@ncyO@erf=\skip61
+\f@ncyO@olf=\skip62
+\f@ncyO@orf=\skip63
+)
+
+Package Fancyhdr Warning: \fancyfoot's `E' option without twoside option is use
+less on input line 55.
+
+\@indexfile=\write4
+\openout4 = `Project1.idx'.
+
+Writing index file Project1.idx
+(/usr/share/texlive/texmf-dist/tex/latex/idxlayout/idxlayout.sty
+Package: idxlayout 2012/03/30 v0.4d Configurable index layout
+
+(/usr/share/texlive/texmf-dist/tex/latex/etoolbox/etoolbox.sty
+Package: etoolbox 2015/08/02 v2.2a e-TeX tools for LaTeX (JAW)
+\etb@tempcnta=\count123
+)
+(/usr/share/texlive/texmf-dist/tex/latex/tools/multicol.sty
+Package: multicol 2015/08/19 v1.8n multicolumn formatting (FMi)
+\c@tracingmulticols=\count124
+\mult@box=\box33
+\multicol@leftmargin=\dimen127
+\c@unbalance=\count125
+\c@collectmore=\count126
+\doublecol@number=\count127
+\multicoltolerance=\count128
+\multicolpretolerance=\count129
+\full@width=\dimen128
+\page@free=\dimen129
+\premulticols=\dimen130
+\postmulticols=\dimen131
+\multicolsep=\skip64
+\multicolbaselineskip=\skip65
+\partial@page=\box34
+\last@line=\box35
+\maxbalancingoverflow=\dimen132
+\mult@rightbox=\box36
+\mult@grightbox=\box37
+\mult@gfirstbox=\box38
+\mult@firstbox=\box39
+\@tempa=\box40
+\@tempa=\box41
+\@tempa=\box42
+\@tempa=\box43
+\@tempa=\box44
+\@tempa=\box45
+\@tempa=\box46
+\@tempa=\box47
+\@tempa=\box48
+\@tempa=\box49
+\@tempa=\box50
+\@tempa=\box51
+\@tempa=\box52
+\@tempa=\box53
+\@tempa=\box54
+\@tempa=\box55
+\@tempa=\box56
+\c@columnbadness=\count130
+\c@finalcolumnbadness=\count131
+\last@try=\dimen133
+\multicolovershoot=\dimen134
+\multicolundershoot=\dimen135
+\mult@nat@firstbox=\box57
+\colbreak@box=\box58
+\mc@col@check@num=\count132
+)
+\c@idxcols=\count133
+\indexcolsep=\skip66
+\indexrule=\skip67
+\ila@indentunit=\skip68
+\ila@initsep=\skip69
+)
+(/usr/share/texlive/texmf-dist/tex/latex/tocbibind/tocbibind.sty
+Package: tocbibind 2010/10/13 v1.5k extra ToC listings
+Package tocbibind Info: The document has section divisions on input line 50.
+
+
+Package tocbibind Note: Using section or other style headings.
+
+) (/usr/share/texlive/texmf-dist/tex/latex/ms/ragged2e.sty
+Package: ragged2e 2009/05/21 v2.1 ragged2e Package (MS)
+
+(/usr/share/texlive/texmf-dist/tex/latex/ms/everysel.sty
+Package: everysel 2011/10/28 v1.2 EverySelectfont Package (MS)
+)
+\CenteringLeftskip=\skip70
+\RaggedLeftLeftskip=\skip71
+\RaggedRightLeftskip=\skip72
+\CenteringRightskip=\skip73
+\RaggedLeftRightskip=\skip74
+\RaggedRightRightskip=\skip75
+\CenteringParfillskip=\skip76
+\RaggedLeftParfillskip=\skip77
+\RaggedRightParfillskip=\skip78
+\JustifyingParfillskip=\skip79
+\CenteringParindent=\skip80
+\RaggedLeftParindent=\skip81
+\RaggedRightParindent=\skip82
+\JustifyingParindent=\skip83
+)
+No file Project1.aux.
+\openout1 = `Project1.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 90.
+LaTeX Font Info: ... okay on input line 90.
+LaTeX Font Info: Try loading font information for T1+lmr on input line 90.
+(/usr/share/texmf/tex/latex/lm/t1lmr.fd
+File: t1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+(/usr/share/texlive/texmf-dist/tex/context/base/supp-pdf.mkii
+[Loading MPS to PDF converter (version 2006.09.02).]
+\scratchcounter=\count134
+\scratchdimen=\dimen136
+\scratchbox=\box59
+\nofMPsegments=\count135
+\nofMParguments=\count136
+\everyMPshowfont=\toks30
+\MPscratchCnt=\count137
+\MPscratchDim=\dimen137
+\MPnumerator=\count138
+\makeMPintoPDFobject=\count139
+\everyMPtoPDFconversion=\toks31
+)
+LaTeX Info: Redefining \microtypecontext on input line 90.
+Package microtype Info: Generating PDF output.
+Package microtype Info: Character protrusion enabled (level 2).
+Package microtype Info: Using default protrusion set `alltext'.
+Package microtype Info: Automatic font expansion enabled (level 2),
+(microtype) stretch: 20, shrink: 20, step: 1, non-selected.
+Package microtype Info: Using default expansion set `basictext'.
+Package microtype Info: No adjustment of tracking.
+Package microtype Info: No adjustment of interword spacing.
+Package microtype Info: No adjustment of character kerning.
+ (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-cmr.cfg
+File: mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman
+(RS)
+)
+(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty
+Package: epstopdf-base 2010/02/09 v2.5 Base part for package epstopdf
+
+(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/grfext.sty
+Package: grfext 2010/08/19 v1.1 Manage graphics extensions (HO)
+)
+Package grfext Info: Graphics extension search list:
+(grfext) [.png,.pdf,.jpg,.mps,.jpeg,.jbig2,.jb2,.PNG,.PDF,.JPG,.JPE
+G,.JBIG2,.JB2,.eps]
+(grfext) \AppendGraphicsExtensions on input line 452.
+
+(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg
+File: epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Liv
+e
+))
+(/usr/share/texlive/texmf-dist/tex/latex/ucs/ucsencs.def
+File: ucsencs.def 2011/01/21 Fixes to fontencodings LGR, T3
+)
+\AtBeginShipoutBox=\box60
+Package hyperref Info: Link coloring ON on input line 90.
+
+(/usr/share/texlive/texmf-dist/tex/latex/hyperref/nameref.sty
+Package: nameref 2012/10/27 v2.43 Cross-referencing by name of section
+
+(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/gettitlestring.sty
+Package: gettitlestring 2010/12/03 v1.4 Cleanup title references (HO)
+)
+\c@section@level=\count140
+)
+LaTeX Info: Redefining \ref on input line 90.
+LaTeX Info: Redefining \pageref on input line 90.
+LaTeX Info: Redefining \nameref on input line 90.
+\@outlinefile=\write5
+\openout5 = `Project1.out'.
+
+
+ABD: EverySelectfont initializing macros
+LaTeX Info: Redefining \selectfont on input line 90.
+LaTeX Font Info: Try loading font information for OT1+lmr on input line 155.
+
+
+(/usr/share/texmf/tex/latex/lm/ot1lmr.fd
+File: ot1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+LaTeX Font Info: Try loading font information for OML+lmm on input line 155.
+
+
+(/usr/share/texmf/tex/latex/lm/omllmm.fd
+File: omllmm.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+LaTeX Font Info: Try loading font information for OMS+lmsy on input line 155
+.
+
+(/usr/share/texmf/tex/latex/lm/omslmsy.fd
+File: omslmsy.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+LaTeX Font Info: Try loading font information for OMX+lmex on input line 155
+.
+
+(/usr/share/texmf/tex/latex/lm/omxlmex.fd
+File: omxlmex.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+LaTeX Font Info: External font `lmex10' loaded for size
+(Font) <10> on input line 155.
+LaTeX Font Info: External font `lmex10' loaded for size
+(Font) <7> on input line 155.
+LaTeX Font Info: External font `lmex10' loaded for size
+(Font) <5> on input line 155.
+LaTeX Font Info: Try loading font information for U+msa on input line 155.
+
+(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd
+File: umsa.fd 2013/01/14 v3.01 AMS symbols A
+)
+(/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msa.cfg
+File: mt-msa.cfg 2006/02/04 v1.1 microtype config. file: AMS symbols (a) (RS)
+)
+LaTeX Font Info: Try loading font information for U+msb on input line 155.
+
+(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd
+File: umsb.fd 2013/01/14 v3.01 AMS symbols B
+)
+(/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msb.cfg
+File: mt-msb.cfg 2005/06/01 v1.0 microtype config. file: AMS symbols (b) (RS)
+)
+LaTeX Font Info: Try loading font information for OMS+lmr on input line 174.
+
+
+(/usr/share/texmf/tex/latex/lm/omslmr.fd
+File: omslmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+LaTeX Font Info: Font shape `OMS/lmr/m/n' in size <8> not available
+(Font) Font shape `OMS/lmsy/m/n' tried instead on input line 174.
+ [1
+
+{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
+LaTeX Font Info: Try loading font information for T1+lmtt on input line 181.
+
+ (/usr/share/texmf/tex/latex/lm/t1lmtt.fd
+File: t1lmtt.fd 2009/10/30 v1.6 Font defs for Latin Modern
+)
+Package microtype Info: Loading generic settings for font family
+(microtype) `lmtt' (encoding: T1).
+(microtype) For optimal results, create family-specific settings.
+(microtype) See the microtype manual for details.
+ [2] [3] [4]
+[5] (/usr/share/texlive/texmf-dist/tex/latex/ucs/data/uni-0.def
+File: uni-0.def 2013/05/13 UCS: Unicode data U+0000..U+00FF
+) [6]
+LaTeX Font Info: Font shape `OMS/lmr/m/n' in size <10> not available
+(Font) Font shape `OMS/lmsy/m/n' tried instead on input line 452.
+ [7]
+[8]
+Package atveryend Info: Empty hook `BeforeClearDocument' on input line 551.
+ [9]
+Package atveryend Info: Empty hook `AfterLastShipout' on input line 551.
+ (./Project1.aux)
+Package atveryend Info: Executing hook `AtVeryEndDocument' on input line 551.
+
+
+ *File List*
+ article.cls 2014/09/29 v1.4h Standard LaTeX document class
+ size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option)
+ relsize.sty 2013/03/29 ver 4.1
+ makeidx.sty 2014/09/29 v1.0m Standard LaTeX package
+ color.sty 1999/02/16
+ color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
+ pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX
+infwarerr.sty 2010/04/08 v1.3 Providing info/warning/error messages (HO)
+ ltxcmds.sty 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
+setspace.sty 2011/12/19 v6.7a set line spacing
+ amsmath.sty 2016/03/03 v2.15a AMS math features
+ amstext.sty 2000/06/29 v2.01 AMS text
+ amsgen.sty 1999/11/30 v2.0 generic functions
+ amsbsy.sty 1999/11/29 v1.2d Bold Symbols
+ amsopn.sty 1999/12/14 v2.01 operator names
+amsfonts.sty 2013/01/14 v3.01 Basic AMSFonts support
+ amssymb.sty 2013/01/14 v3.01 AMS font symbols
+ xcolor.sty 2007/01/21 v2.11 LaTeX color extensions (UK)
+ color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
+colortbl.sty 2012/02/13 v1.0a Color table columns (DPC)
+ array.sty 2014/10/28 v2.4c Tabular extension package (FMi)
+ bm.sty 2014/10/28 v1.1c Bold Symbol Support (DPC/FMi)
+ ltablex.sty 2014/08/13 v1.1 Modified tabularx
+longtable.sty 2014/10/28 v4.11 Multi-page Table package (DPC)
+tabularx.sty 2014/10/28 v2.10 `tabularx' package (DPC)
+microtype.sty 2013/05/23 v2.5a Micro-typographical refinements (RS)
+ keyval.sty 2014/10/28 v1.15 key=value parser (DPC)
+microtype-pdftex.def 2013/05/23 v2.5a Definitions specific to pdftex (RS)
+microtype.cfg 2013/05/23 v2.5a microtype main configuration file (RS)
+graphicx.sty 2014/10/28 v1.0g Enhanced LaTeX Graphics (DPC,SPQR)
+graphics.sty 2016/01/03 v1.0q Standard LaTeX Graphics (DPC,SPQR)
+ trig.sty 2016/01/03 v1.10 sin cos tan (DPC)
+graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
+fancyvrb.sty 2008/02/07
+ fontenc.sty
+ t1enc.def 2005/09/27 v1.99g Standard LaTeX file
+ ucs.sty 2013/05/11 v2.2 UCS: Unicode input support
+uni-global.def 2013/05/13 UCS: Unicode global data
+inputenc.sty 2015/03/17 v1.2c Input encoding file
+ utf8x.def 2004/10/17 UCS: Input encoding UTF-8
+ lmodern.sty 2009/10/30 v1.6 Latin Modern Fonts
+hyperref.sty 2012/11/06 v6.83m Hypertext links for LaTeX
+hobsub-hyperref.sty 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO)
+hobsub-generic.sty 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO)
+ hobsub.sty 2012/05/28 v1.13 Construct package bundles (HO)
+ifluatex.sty 2010/03/01 v1.3 Provides the ifluatex switch (HO)
+ ifvtex.sty 2010/03/01 v1.5 Detect VTeX and its facilities (HO)
+ intcalc.sty 2007/09/27 v1.1 Expandable calculations with integers (HO)
+ ifpdf.sty 2011/01/30 v2.3 Provides the ifpdf switch (HO)
+etexcmds.sty 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
+kvsetkeys.sty 2012/04/25 v1.16 Key value parser (HO)
+kvdefinekeys.sty 2011/04/07 v1.3 Define keys (HO)
+pdftexcmds.sty 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO)
+pdfescape.sty 2011/11/25 v1.13 Implements pdfTeX's escape features (HO)
+bigintcalc.sty 2012/04/08 v1.3 Expandable calculations on big integers (HO)
+ bitset.sty 2011/01/30 v1.1 Handle bit-vector datatype (HO)
+uniquecounter.sty 2011/01/30 v1.2 Provide unlimited unique counter (HO)
+letltxmacro.sty 2010/09/02 v1.4 Let assignment for LaTeX macros (HO)
+ hopatch.sty 2012/05/28 v1.2 Wrapper for package hooks (HO)
+xcolor-patch.sty 2011/01/30 xcolor patch
+atveryend.sty 2011/06/30 v1.8 Hooks at the very end of document (HO)
+atbegshi.sty 2011/10/05 v1.16 At begin shipout hook (HO)
+refcount.sty 2011/10/16 v3.4 Data extraction from label references (HO)
+ hycolor.sty 2011/01/30 v1.7 Color options for hyperref/bookmark (HO)
+ ifxetex.sty 2010/09/12 v0.6 Provides ifxetex conditional
+ auxhook.sty 2011/03/04 v1.3 Hooks for auxiliary files (HO)
+kvoptions.sty 2011/06/30 v3.11 Key value format for package options (HO)
+ pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO)
+hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive
+ url.sty 2013/09/16 ver 3.4 Verb mode for urls, etc.
+ hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX
+rerunfilecheck.sty 2011/04/15 v1.7 Rerun checks for auxiliary files (HO)
+fancyhdr.sty
+idxlayout.sty 2012/03/30 v0.4d Configurable index layout
+etoolbox.sty 2015/08/02 v2.2a e-TeX tools for LaTeX (JAW)
+multicol.sty 2015/08/19 v1.8n multicolumn formatting (FMi)
+tocbibind.sty 2010/10/13 v1.5k extra ToC listings
+ragged2e.sty 2009/05/21 v2.1 ragged2e Package (MS)
+everysel.sty 2011/10/28 v1.2 EverySelectfont Package (MS)
+ t1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+supp-pdf.mkii
+ mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman (
+RS)
+epstopdf-base.sty 2010/02/09 v2.5 Base part for package epstopdf
+ grfext.sty 2010/08/19 v1.1 Manage graphics extensions (HO)
+epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live
+ ucsencs.def 2011/01/21 Fixes to fontencodings LGR, T3
+ nameref.sty 2012/10/27 v2.43 Cross-referencing by name of section
+gettitlestring.sty 2010/12/03 v1.4 Cleanup title references (HO)
+ ot1lmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ omllmm.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ omslmsy.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ omxlmex.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ umsa.fd 2013/01/14 v3.01 AMS symbols A
+ mt-msa.cfg 2006/02/04 v1.1 microtype config. file: AMS symbols (a) (RS)
+ umsb.fd 2013/01/14 v3.01 AMS symbols B
+ mt-msb.cfg 2005/06/01 v1.0 microtype config. file: AMS symbols (b) (RS)
+ omslmr.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ t1lmtt.fd 2009/10/30 v1.6 Font defs for Latin Modern
+ uni-0.def 2013/05/13 UCS: Unicode data U+0000..U+00FF
+ ***********
+
+Package atveryend Info: Executing hook `AtEndAfterFileList' on input line 551.
+
+Package rerunfilecheck Warning: File `Project1.out' has changed.
+(rerunfilecheck) Rerun to get outlines right
+(rerunfilecheck) or use package `bookmark'.
+
+Package rerunfilecheck Info: Checksums for `Project1.out':
+(rerunfilecheck) Before:
+(rerunfilecheck) After: D41D8CD98F00B204E9800998ECF8427E;0.
+Package atveryend Info: Empty hook `AtVeryVeryEnd' on input line 551.
+ )
+Here is how much of TeX's memory you used:
+ 10632 strings out of 493029
+ 155761 string characters out of 6136233
+ 291311 words of memory out of 5000000
+ 13835 multiletter control sequences out of 15000+600000
+ 66983 words of font info for 101 fonts, out of 8000000 for 9000
+ 1141 hyphenation exceptions out of 8191
+ 41i,15n,43p,1001b,479s stack positions out of 5000i,500n,10000p,200000b,80000s
+{/usr/share/texmf/fonts/enc/dvips/lm/lm-rm.enc}{/usr/share/texmf/fonts/enc/dv
+ips/lm/lm-mathsy.enc}{/usr/share/texmf/fonts/enc/dvips/lm/lm-mathit.enc}{/usr/s
+hare/texmf/fonts/enc/dvips/lm/lm-ec.enc}{/usr/share/texmf/fonts/enc/dvips/lm/lm
+-mathex.enc}
+Output written on Project1.pdf (9 pages, 281972 bytes).
+PDF statistics:
+ 168 PDF objects out of 1000 (max. 8388607)
+ 138 compressed objects within 2 object streams
+ 29 named destinations out of 1000 (max. 500000)
+ 19969 words of extra memory for PDF output out of 20736 (max. 10000000)
+
diff --git a/doc/Projects/2020/Project1/pdf/Project1.out b/doc/Projects/2020/Project1/pdf/Project1.out
new file mode 100644
index 000000000..e69de29bb
diff --git a/doc/Projects/2020/Project1/pdf/Project1.p.tex b/doc/Projects/2020/Project1/pdf/Project1.p.tex
index 49aadf5f9..5a37d4a7c 100644
--- a/doc/Projects/2020/Project1/pdf/Project1.p.tex
+++ b/doc/Projects/2020/Project1/pdf/Project1.p.tex
@@ -155,7 +155,7 @@ Project 1 on Machine Learning, deadline October 5, 2020
% --- begin date ---
\begin{center}
-Sep 7, 2020
+Sep 16, 2020
\end{center}
% --- end date ---
@@ -370,19 +370,15 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
-
-
+data.
Implement the $k$-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
\textbf{Scikit-Learn} if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your \textbf{bootstrap} code.
-You can also compare your own cross-validation code with the one provided by \textbf{Scikit-Learn}.
+Compare the MSE you get from your cross-validation code with the one you got from your \textbf{bootstrap} code. Comment your results. Try $5-10$ folds.
+You can also compare your own cross-validation code with the one provided by \textbf{Scikit-Learn}.
\paragraph{Part d): Ridge Regression on the Franke function with resampling.}
diff --git a/doc/Projects/2020/Project1/pdf/Project1.pdf b/doc/Projects/2020/Project1/pdf/Project1.pdf
index 1a5e858b0..435588da4 100644
Binary files a/doc/Projects/2020/Project1/pdf/Project1.pdf and b/doc/Projects/2020/Project1/pdf/Project1.pdf differ
diff --git a/doc/Projects/2020/Project1/pdf/Project1.tex b/doc/Projects/2020/Project1/pdf/Project1.tex
index d3545c882..8e281e154 100644
--- a/doc/Projects/2020/Project1/pdf/Project1.tex
+++ b/doc/Projects/2020/Project1/pdf/Project1.tex
@@ -125,7 +125,7 @@ Project 1 on Machine Learning, deadline October 5, 2020
% --- begin date ---
\begin{center}
-Sep 7, 2020
+Sep 16, 2020
\end{center}
% --- end date ---
@@ -227,7 +227,7 @@ We will generate our own dataset for a function
$\mathrm{FrankeFunction}(x,y)$ with $x,y \in [0,1]$. The function
$f(x,y)$ is the Franke function. You should explore also the addition
of an added stochastic noise to this function using the normal
-distribution $\cal{N}(0,1)$.
+distribution $N(0,1)$.
\emph{Write your own code} (using either a matrix inversion or a singular
value decomposition from e.g., \textbf{numpy} ) or use your code from
@@ -340,19 +340,15 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
-
-
+data.
Implement the $k$-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
\textbf{Scikit-Learn} if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your \textbf{bootstrap} code.
-You can also compare your own cross-validation code with the one provided by \textbf{Scikit-Learn}.
+Compare the MSE you get from your cross-validation code with the one you got from your \textbf{bootstrap} code. Comment your results. Try $5-10$ folds.
+You can also compare your own cross-validation code with the one provided by \textbf{Scikit-Learn}.
\paragraph{Part d): Ridge Regression on the Franke function with resampling.}
diff --git a/doc/Projects/2020/hw2/ipynb/hw2.ipynb b/doc/Projects/2020/hw2/ipynb/hw2.ipynb
new file mode 100644
index 000000000..69326ca8c
--- /dev/null
+++ b/doc/Projects/2020/hw2/ipynb/hw2.ipynb
@@ -0,0 +1,740 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "# Homework 2, weeks 36 and 37\n",
+ "\n",
+ " \n",
+ "**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n",
+ "\n",
+ "Date: **Sep 8, 2020**\n",
+ "\n",
+ "Copyright 1999-2020, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Exercise 1: Adding Ridge and Lasso Regression\n",
+ "\n",
+ "This exercise is a continuation of exercise 3 from exercise set 1 (week 35). We will\n",
+ "use the same function to generate our data set, still staying with a\n",
+ "simple function $y(x)$ which we want to fit using linear regression,\n",
+ "but now extending the analysis to include the Ridge and the Lasso\n",
+ "regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the [regression slides](https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html)). \n",
+ "\n",
+ "We will thus again generate our own dataset for a function $y(x)$ where \n",
+ "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n",
+ "distribution. The function $y$ is a quadratic polynomial in $x$ with\n",
+ "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n",
+ "\n",
+ "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**a)**\n",
+ "Write your own code for the Ridge method (see chapter 3.4 of Hastie *et al.*, equations (3.43) and (3.44)) and compute the parametrization for different values of $\\lambda$. Compare and analyze your results with those from exercise 3. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "The code here allows you to perform your own Ridge calculation and perform calculations for various values of the regularization parameter $\\lambda$. This program can easily be extended upon."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training R2 for OLS\")\n",
+ "print(R2(y_train,ytildeOLS))\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test R2 for OLS\")\n",
+ "print(R2(y_test,ypredictOLS))\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 20\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "**b)**\n",
+ "Repeat the above but using the functionality of **Scikit-Learn**. Compare your code with the results from **Scikit-Learn**. Remember to run with the same random numbers for generating $x$ and $y$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "To use **scikit-learn** with Ridge, we simply need to add the relevant function **Ridge()**, as done in the code here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import sklearn.linear_model as skl\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training R2 for OLS\")\n",
+ "print(R2(y_train,ytildeOLS))\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test R2 for OLS\")\n",
+ "print(R2(y_test,ypredictOLS))\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSEPredictSKL = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 0, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # add ridge\n",
+ " clf_ridge = skl.Ridge(alpha=lmb).fit(X_train, y_train)\n",
+ " yridge = clf_ridge.predict(X_test)\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSEPredictSKL[i] = MSE(y_test,yridge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ "#then plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSEPredictSKL, 'g--', label = 'MSE Ridge sickit-learn Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "**c)**\n",
+ "Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using **Scikit-Learn** to find the parameters $\\beta$. From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$). Discuss the results of these variances as functions of $\\lambda$. In particular, try to link your discussion with the discussion in Hastie *et al.* and their figures 3.10 and 3.11. **Scikit-Learn** may not provide the variance of the parameters $\\beta$. This needs to be checked. With your own code you can however do so.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import sklearn.linear_model as skl\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# The variance is given by the inverse of the matrix X^TX\n",
+ "print(np.linalg.inv(X_train.T @ X_train))\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 10\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSEPredictSKL = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 0, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " print(np.linalg.inv(X_train.T @ X_train+lmb*I))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "**d)**\n",
+ "Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie *et al.*. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of **scikit-learn**. We recommend the latter since we have not yet discussed how to solve the Lasso equations numerically. Also, you do not need to compute the variance of the parameters $\\beta$ but you can extract their values and study their behavior as functions of the regularization parameter $\\lambda$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import sklearn.linear_model as skl\n",
+ "#from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training R2 for OLS\")\n",
+ "print(R2(y_train,ytildeOLS))\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test R2 for OLS\")\n",
+ "print(R2(y_test,ypredictOLS))\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredictLasso = np.zeros(nlambdas)\n",
+ "MSEPredictRidge = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 0, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # add ridge\n",
+ " clf_ridge = skl.Ridge(alpha=lmb).fit(X_train, y_train)\n",
+ " clf_lasso = skl.Lasso(alpha=lmb).fit(X_train, y_train)\n",
+ " yridge = clf_ridge.predict(X_test)\n",
+ " ylasso = clf_lasso.predict(X_test)\n",
+ " MSEPredictLasso[i] = MSE(y_test,ylasso)\n",
+ " MSEPredictRidge[i] = MSE(y_test,yridge)\n",
+ "#then plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEPredictRidge, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSEPredictLasso, 'g--', label = 'MSE Lasso Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "**e)**\n",
+ "Finally, using **Scikit-Learn** or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n",
+ "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the $R^2$ score function.\n",
+ "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined the mean value of $\\hat{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Discuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "These results can all be studied with the codes we have above. These scores are included in the codes above.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Exercise 2: Normalizing our data\n",
+ "\n",
+ "A much used approach before starting to train the data is to preprocess our\n",
+ "data. Normally the data may need a rescaling and/or may be sensitive\n",
+ "to extreme values. Scaling the data renders our inputs much more\n",
+ "suitable for the algorithms we want to employ.\n",
+ "\n",
+ "**Scikit-Learn** has several functions which allow us to rescale the\n",
+ "data, normally resulting in much better results in terms of various\n",
+ "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n",
+ "ensures that for each feature/predictor we study the mean value is\n",
+ "zero and the variance is one (every column in the design/feature\n",
+ "matrix). This scaling has the drawback that it does not ensure that\n",
+ "we have a particular maximum or minimum in our data set. Another\n",
+ "function included in **Scikit-Learn** is the **MinMaxScaler** which\n",
+ "ensures that all features are exactly between $0$ and $1$. The\n",
+ "\n",
+ "\n",
+ "The **Normalizer** scales each data\n",
+ "point such that the feature vector has a euclidean length of one. In other words, it\n",
+ "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n",
+ "radius of 1. This means every data point is scaled by a different number (by the\n",
+ "inverse of it’s length).\n",
+ "This normalization is often used when only the direction (or angle) of the data matters,\n",
+ "not the length of the feature vector.\n",
+ "\n",
+ "The **RobustScaler** works similarly to the StandardScaler in that it\n",
+ "ensures statistical properties for each feature that guarantee that\n",
+ "they are on the same scale. However, the RobustScaler uses the median\n",
+ "and quartiles, instead of mean and variance. This makes the\n",
+ "RobustScaler ignore data points that are very different from the rest\n",
+ "(like measurement errors). These odd data points are also called\n",
+ "outliers, and might often lead to trouble for other scaling\n",
+ "techniques.\n",
+ "\n",
+ "\n",
+ "It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\\%$ of the data for training and the rest\n",
+ "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# split in training and test data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then we can use the standard scaler to scale our data as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this exercise we want you to to compute the MSE for the training\n",
+ "data and the test data as function of the complexity of a polynomial,\n",
+ "that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n",
+ "\n",
+ "One of \n",
+ "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n",
+ "We will also use Ridge and Lasso regression. \n",
+ "\n",
+ "\n",
+ "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "np.random.seed()\n",
+ "n = 100\n",
+ "maxdegree = 14\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $y$ is the function we want to fit with a given polynomial.\n",
+ "\n",
+ "\n",
+ "**a)**\n",
+ "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "n = 50\n",
+ "maxdegree = 5\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "TestError = np.zeros(maxdegree)\n",
+ "TrainError = np.zeros(maxdegree)\n",
+ "polydegree = np.zeros(maxdegree)\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "x_train_scaled = scaler.transform(x_train)\n",
+ "x_test_scaled = scaler.transform(x_test)\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " clf = model.fit(x_train_scale,y_train)\n",
+ " y_fit = clf.predict(x_train_scaled)\n",
+ " y_pred = clf.predict(x_test_scaled) \n",
+ " polydegree[degree] = degree\n",
+ " TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n",
+ " TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )\n",
+ "\n",
+ "plt.plot(polydegree, TestError, label='Test Error')\n",
+ "plt.plot(polydegree, TrainError, label='Train Error')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "**b)**\n",
+ "Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "This requires a simple extension to the above code where you simply add a statement calling the $R2$ function included in the same code.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**c)**\n",
+ "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "Here you simply need to change the degree of the polynomial in the above code to $n=15$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**d)**\n",
+ "Repeat part (2c) but now using Ridge regressions with various hyperparameters $\\lambda$. Make the same plots for the optimal $\\lambda$ value for each polynomial degree. Compare these results with those from the standard OLS approach.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Solution.**\n",
+ "Here you need to add for example the same loop over the parameters $\\lambda$ as you did in the first exercise, that is add"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "nlambdas = 100\n",
+ "MSEPredictRidge = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 0, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # add ridge\n",
+ " clf_ridge = skl.Ridge(alpha=lmb).fit(X_train_scaled, y_train)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The plotting functionality of the first exercise can be reused here as well.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ ""
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/doc/Projects/2020/hw2/pdf/hw2.idx b/doc/Projects/2020/hw2/pdf/hw2.idx
new file mode 100644
index 000000000..e69de29bb
diff --git a/doc/src/Projects/2020/Project1/Project1.do.txt b/doc/src/Projects/2020/Project1/Project1.do.txt
index 53dc0b901..2909c3757 100644
--- a/doc/src/Projects/2020/Project1/Project1.do.txt
+++ b/doc/src/Projects/2020/Project1/Project1.do.txt
@@ -230,19 +230,15 @@ Note also that when you calculate the bias, in all applications you don't know t
The aim here is to write your own code for another widely popular
resampling technique, the so-called cross-validation method. Again,
before you start with cross-validation approach, you should scale your
-data and split it in test and training data as you did earlier.
-Perform a resampling of the data where you split the data in training
-data and test data using for example
-
-
+data.
Implement the $k$-fold cross-validation algorithm (write your own
code) and evaluate again the MSE function resulting
-from the test data. You can compare your own code with that from
+from the test folds. You can compare your own code with that from
_Scikit-Learn_ if needed.
-Compare the MSE you get from your cross-validation code with the one you got from your _bootstrap_ code.
-You can also compare your own cross-validation code with the one provided by _Scikit-Learn_.
+Compare the MSE you get from your cross-validation code with the one you got from your _bootstrap_ code. Comment your results. Try $5-10$ folds.
+You can also compare your own cross-validation code with the one provided by _Scikit-Learn_.
=== Part d): Ridge Regression on the Franke function with resampling ===
diff --git a/doc/src/week39/week39.do.txt b/doc/src/week39/week39.do.txt
new file mode 100644
index 000000000..b1c7f8dcb
--- /dev/null
+++ b/doc/src/week39/week39.do.txt
@@ -0,0 +1,1989 @@
+TITLE: Week 39: Optimization and Gradient Methods
+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
+
+!split
+===== Plan for week 39 =====
+
+* Thursday: Repetition of Logistic regression equations and discussion of Gradient methods
+* Friday: Stochastic Gradient descent with examples and automatic differeantion
+
+!split
+===== Thursday September 24 =====
+
+!split
+===== Optimization, the central part of any Machine Learning algortithm =====
+
+Almost every problem in machine learning and data science starts with
+a dataset $X$, a model $g(\beta)$, which is a function of the
+parameters $\beta$ and a cost function $C(X, g(\beta))$ that allows
+us to judge how well the model $g(\beta)$ explains the observations
+$X$. The model is fit by finding the values of $\beta$ that minimize
+the cost function. Ideally we would be able to solve for $\beta$
+analytically, however this is not possible in general and we must use
+some approximative/numerical method to compute the minimum.
+
+
+!split
+===== Revisiting our Logistic Regression case =====
+
+In our discussion on Logistic Regression we studied the
+case of
+two classes, with $y_i$ either
+$0$ or $1$. Furthermore we assumed also that we have only two
+parameters $\beta$ in our fitting, that is we
+defined probabilities
+
+!bt
+\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*}
+!et
+where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$.
+
+!split
+===== The equations to solve =====
+
+Our compact equations used a definition of 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 rewrote in a more compact form
+the first derivative of the cost function as
+
+!bt
+\[
+\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right).
+\]
+!et
+
+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
+
+!bt
+\[
+\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}.
+\]
+!et
+This defines what is called the Hessian matrix.
+
+!split
+===== Solving using Newton-Raphson's method =====
+
+If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives.
+
+Our iterative scheme is then given by
+
+!bt
+\[
+\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T}\right)^{-1}_{\hat{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}}\right)_{\hat{\beta}^{\mathrm{old}}},
+\]
+!et
+or in matrix form as
+
+!bt
+\[
+\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\hat{X}^T\hat{W}\hat{X} \right)^{-1}\times \left(-\hat{X}^T(\hat{y}-\hat{p}) \right)_{\hat{\beta}^{\mathrm{old}}}.
+\]
+!et
+The right-hand side is computed with the old values of $\beta$.
+
+If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement.
+
+
+!split
+===== Brief reminder on Newton-Raphson's method =====
+
+Let us quickly remind ourselves how we derive the above method.
+
+Perhaps the most celebrated of all one-dimensional root-finding
+routines is Newton's method, also called the Newton-Raphson
+method. This method requires the evaluation of both the
+function $f$ and its derivative $f'$ at arbitrary points.
+If you can only calculate the derivative
+numerically and/or your function is not of the smooth type, we
+normally discourage the use of this method.
+
+!split
+===== The equations =====
+
+The Newton-Raphson formula consists geometrically of extending the
+tangent line at a current point until it crosses zero, then setting
+the next guess to the abscissa of that zero-crossing. The mathematics
+behind this method is rather simple. Employing a Taylor expansion for
+$x$ sufficiently close to the solution $s$, we have
+
+
+!bt
+\[
+ f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots.
+ \label{eq:taylornr}
+\]
+!et
+
+For small enough values of the function and for well-behaved
+functions, the terms beyond linear are unimportant, hence we obtain
+
+
+!bt
+\[
+ f(x)+(s-x)f'(x)\approx 0,
+\]
+!et
+yielding
+!bt
+\[
+ s\approx x-\frac{f(x)}{f'(x)}.
+\]
+!et
+
+Having in mind an iterative procedure, it is natural to start iterating with
+!bt
+\[
+ x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}.
+\]
+!et
+
+!split
+===== Simple geometric interpretation =====
+
+The above is Newton-Raphson's method. It has a simple geometric
+interpretation, namely $x_{n+1}$ is the point where the tangent from
+$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,
+Newton-Raphson converges fast to the desired result. However, if we
+are far from a root, where the higher-order terms in the series are
+important, the Newton-Raphson formula can give grossly inaccurate
+results. For instance, the initial guess for the root might be so far
+from the true root as to let the search interval include a local
+maximum or minimum of the function. If an iteration places a trial
+guess near such a local extremum, so that the first derivative nearly
+vanishes, then Newton-Raphson may fail totally
+
+
+!split
+===== Extending to more than one variable =====
+
+Newton's method can be generalized to systems of several non-linear equations
+and variables. Consider the case with two equations
+!bt
+\[
+ \begin{array}{cc} f_1(x_1,x_2) &=0\\
+ f_2(x_1,x_2) &=0,\end{array}
+\]
+!et
+which we Taylor expand to obtain
+
+!bt
+\[
+ \begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1
+ \partial f_1/\partial x_1+h_2
+ \partial f_1/\partial x_2+\dots\\
+ 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1
+ \partial f_2/\partial x_1+h_2
+ \partial f_2/\partial x_2+\dots
+ \end{array}.
+\]
+!et
+Defining the Jacobian matrix ${\bf \hat{J}}$ we have
+!bt
+\[
+ {\bf \hat{J}}=\left( \begin{array}{cc}
+ \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\
+ \partial f_2/\partial x_1 &\partial f_2/\partial x_2
+ \end{array} \right),
+\]
+!et
+we can rephrase Newton's method as
+!bt
+\[
+\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)=
+\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+
+\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right),
+\]
+!et
+where we have defined
+!bt
+\[
+ \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)=
+ -{\bf \hat{J}}^{-1}
+ \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right).
+\]
+!et
+We need thus to compute the inverse of the Jacobian matrix and it
+is to understand that difficulties may
+arise in case ${\bf \hat{J}}$ is nearly singular.
+
+It is rather straightforward to extend the above scheme to systems of
+more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function.
+
+
+
+!split
+===== Steepest descent =====
+
+The basic idea of gradient descent is
+that a function $F(\mathbf{x})$,
+$\mathbf{x} \equiv (x_1,\cdots,x_n)$, decreases fastest if one goes from $\bf {x}$ in the
+direction of the negative gradient $-\nabla F(\mathbf{x})$.
+
+It can be shown that if
+!bt
+\[
+\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k),
+\]
+!et
+with $\gamma_k > 0$.
+
+For $\gamma_k$ small enough, then $F(\mathbf{x}_{k+1}) \leq
+F(\mathbf{x}_k)$. This means that for a sufficiently small $\gamma_k$
+we are always moving towards smaller function values, i.e a minimum.
+
+!split
+===== More on Steepest descent =====
+
+The previous observation is the basis of the method of steepest
+descent, which is also referred to as just gradient descent (GD). One
+starts with an initial guess $\mathbf{x}_0$ for a minimum of $F$ and
+computes new approximations according to
+
+!bt
+\[
+\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0.
+\]
+!et
+
+The parameter $\gamma_k$ is often referred to as the step length or
+the learning rate within the context of Machine Learning.
+
+!split
+===== The ideal =====
+
+Ideally the sequence $\{\mathbf{x}_k \}_{k=0}$ converges to a global
+minimum of the function $F$. In general we do not know if we are in a
+global or local minimum. In the special case when $F$ is a convex
+function, all local minima are also global minima, so in this case
+gradient descent can converge to the global solution. The advantage of
+this scheme is that it is conceptually simple and straightforward to
+implement. However the method in this form has some severe
+limitations:
+
+In machine learing we are often faced with non-convex high dimensional
+cost functions with many local minima. Since GD is deterministic we
+will get stuck in a local minimum, if the method converges, unless we
+have a very good intial guess. This also implies that the scheme is
+sensitive to the chosen initial condition.
+
+Note that the gradient is a function of $\mathbf{x} =
+(x_1,\cdots,x_n)$ which makes it expensive to compute numerically.
+
+
+!split
+===== The sensitiveness of the gradient descent =====
+
+The gradient descent method
+is sensitive to the choice of learning rate $\gamma_k$. This is due
+to the fact that we are only guaranteed that $F(\mathbf{x}_{k+1}) \leq
+F(\mathbf{x}_k)$ for sufficiently small $\gamma_k$. The problem is to
+determine an optimal learning rate. If the learning rate is chosen too
+small the method will take a long time to converge and if it is too
+large we can experience erratic behavior.
+
+Many of these shortcomings can be alleviated by introducing
+randomness. One such method is that of Stochastic Gradient Descent
+(SGD), see below.
+
+
+!split
+===== Convex functions =====
+
+Ideally we want our cost/loss function to be convex(concave).
+
+First we give the definition of a convex set: A set $C$ in
+$\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and
+all $t \in (0,1)$ , the point $(1 − t)x + ty$ also belongs to
+C. Geometrically this means that every point on the line segment
+connecting $x$ and $y$ is in $C$ as discussed below.
+
+The convex subsets of $\mathbb{R}$ are the intervals of
+$\mathbb{R}$. Examples of convex sets of $\mathbb{R}^2$ are the
+regular polygons (triangles, rectangles, pentagons, etc...).
+
+!split
+===== Convex function =====
+
+_Convex function_: Let $X \subset \mathbb{R}^n$ be a convex set. Assume that the function $f: X \rightarrow \mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \in X$ and for all $t \in [0,1]$. If $\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \neq x_2$ and $t\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.
+
+!split
+===== Conditions on convex functions =====
+
+In the following we state first and second-order conditions which
+ensures convexity of a function $f$. We write $D_f$ to denote the
+domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more
+details and proofs we refer to: "S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press":"http://stanford.edu/boyd/cvxbook/, 2004".
+
+!bblock First order condition
+Suppose $f$ is differentiable (i.e $\nabla f(x)$ is well defined for
+all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$
+is a convex set and $$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ holds
+for all $x,y \in D_f$. This condition means that for a convex function
+the first order Taylor expansion (right hand side above) at any point
+a global under estimator of the function. To convince yourself you can
+make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and
+note that it is always below the graph.
+!eblock
+
+!bblock Second order condition
+Assume that $f$ is twice
+differentiable, i.e the Hessian matrix exists at each point in
+$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its
+Hessian is positive semi-definite for all $x\in D_f$. For a
+single-variable function this reduces to $f''(x) \geq 0$. Geometrically this means that $f$ has nonnegative curvature
+everywhere.
+!eblock
+
+This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.
+
+!split
+===== More on convex functions =====
+
+The next result is of great importance to us and the reason why we are
+going on about convex functions. In machine learning we frequently
+have to minimize a loss/cost function in order to find the best
+parameters for the model we are considering.
+
+Ideally we want the
+global minimum (for high-dimensional models it is hard to know
+if we have local or global minimum). However, if the cost/loss function
+is convex the following result provides invaluable information:
+
+!bblock Any minimum is global for convex functions
+Consider the problem of finding $x \in \mathbb{R}^n$ such that $f(x)$
+is minimal, where $f$ is convex and differentiable. Then, any point
+$x^*$ that satisfies $\nabla f(x^*) = 0$ is a global minimum.
+!eblock
+
+This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.
+
+!split
+===== Some simple problems =====
+
+o Show that $f(x)=x^2$ is convex for $x \in \mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \in D_f$ and any $\lambda \in [0,1]$ $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
+
+o Using the second order condition show that the following functions are convex on the specified domain.
+ * $f(x) = e^x$ is convex for $x \in \mathbb{R}$.
+ * $g(x) = -\ln(x)$ is convex for $x \in (0,\infty)$.
+o Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \in \mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.
+
+o A norm is any function that satisfy the following properties
+ * $f(\alpha x) = |\alpha| f(x)$ for all $\alpha \in \mathbb{R}$.
+ * $f(x+y) \leq f(x) + f(y)$
+ * $f(x) \leq 0$ for all $x \in \mathbb{R}^n$ with equality if and only if $x = 0$
+
+Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this).
+
+
+
+!split
+===== Revisiting our first homework =====
+
+We will use linear regression as a case study for the gradient descent
+methods. Linear regression is a great test case for the gradient
+descent methods discussed in the lectures since it has several
+desirable properties such as:
+
+o An analytical solution (recall homework set 1).
+o The gradient can be computed analytically.
+o The cost function is convex which guarantees that gradient descent converges for small enough learning rates
+
+We revisit the example from homework set 1 where we had
+!bt
+\[
+y_i = 5x_i^2 + 0.1\xi_i, \ i=1,\cdots,100
+\]
+!et
+with $x_i \in [0,1] $ chosen randomly with a uniform distribution. Additionally $\xi_i$ represents stochastic noise chosen according to a normal distribution $\cal {N}(0,1)$.
+The linear regression model is given by
+!bt
+\[
+h_\beta(x) = \hat{y} = \beta_0 + \beta_1 x,
+\]
+!et
+such that
+!bt
+\[
+\hat{y}_i = \beta_0 + \beta_1 x_i.
+\]
+!et
+
+!split
+===== Gradient descent example =====
+
+Let $\mathbf{y} = (y_1,\cdots,y_n)^T$, $\mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T$ and $\beta = (\beta_0, \beta_1)^T$
+
+It is convenient to write $\mathbf{\hat{y}} = X\beta$ where $X \in \mathbb{R}^{100 \times 2} $ is the design matrix given by
+!bt
+\[
+X \equiv \begin{bmatrix}
+1 & x_1 \\
+\vdots & \vdots \\
+1 & x_{100} & \\
+\end{bmatrix}.
+\]
+!et
+The loss function is given by
+!bt
+\[
+C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\mathbf{y}||^2 = \sum_{i=1}^{100} (\beta_0 + \beta_1 x_i)^2 - 2 y_i (\beta_0 + \beta_1 x_i) + y_i^2
+\]
+!et
+and we want to find $\beta$ such that $C(\beta)$ is minimized.
+
+!split
+===== The derivative of the cost/loss function =====
+
+Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \partial \beta_1$ we can show that the gradient can be written as
+!bt
+\[
+\nabla_{\beta} C(\beta) = (\partial C(\beta) / \partial \beta_0, \partial C(\beta) / \partial \beta_1)^T = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\
+\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\
+\end{bmatrix} = 2X^T(X\beta - \mathbf{y}),
+\]
+!et
+where $X$ is the design matrix defined above.
+
+!split
+===== The Hessian matrix =====
+The Hessian matrix of $C(\beta)$ is given by
+!bt
+\[
+\hat{H} \equiv \begin{bmatrix}
+\frac{\partial^2 C(\beta)}{\partial \beta_0^2} & \frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} \\
+\frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} & \frac{\partial^2 C(\beta)}{\partial \beta_1^2} & \\
+\end{bmatrix} = 2X^T X.
+\]
+!et
+This result implies that $C(\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.
+
+
+
+
+!split
+===== Simple program =====
+
+We can now write a program that minimizes $C(\beta)$ using the gradient descent method with a constant learning rate $\gamma$ according to
+!bt
+\[
+\beta_{k+1} = \beta_k - \gamma \nabla_\beta C(\beta_k), \ k=0,1,\cdots
+\]
+!et
+
+We can use the expression we computed for the gradient and let use a
+$\beta_0$ be chosen randomly and let $\gamma = 0.001$. Stop iterating
+when $||\nabla_\beta C(\beta_k) || \leq \epsilon = 10^{-8}$.
+
+And finally we can compare our solution for $\beta$ with the analytic result given by
+$\beta= (X^TX)^{-1} X^T \mathbf{y}$.
+
+!split
+===== Gradient Descent Example =====
+
+Here our simple example
+!bc pycod
+
+# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 1000
+
+for iter in range(Niterations):
+ gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)
+ beta -= eta*gradients
+
+print(beta)
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(beta)
+ypredict2 = xbnew.dot(beta_linreg)
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example')
+plt.show()
+
+!ec
+
+!split
+===== And a corresponding example using _scikit-learn_ =====
+
+!bc pycod
+# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+x = 2*np.random.rand(100,1)
+y = 4+3*x+np.random.randn(100,1)
+
+xb = np.c_[np.ones((100,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print(sgdreg.intercept_, sgdreg.coef_)
+
+!ec
+
+
+
+!split
+===== Gradient descent and Ridge =====
+
+We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\beta$,
+!bt
+\[
+C_{\text{ridge}}(\beta) = ||X\beta -\mathbf{y}||^2 + \lambda ||\beta||^2, \ \lambda \geq 0.
+\]
+!et
+
+In order to minimize $C_{\text{ridge}}(\beta)$ using GD we only have adjust the gradient as follows
+!bt
+\[
+\nabla_\beta C_{\text{ridge}}(\beta) = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\
+\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\
+\end{bmatrix} + 2\lambda\begin{bmatrix} \beta_0 \\ \beta_1\end{bmatrix} = 2 (X^T(X\beta - \mathbf{y})+\lambda \beta).
+\]
+!et
+
+We can easily extend our program to minimize $C_{\text{ridge}}(\beta)$ using gradient descent and compare with the analytical solution given by
+!bt
+\[
+\beta_{\text{ridge}} = \left(X^T X + \lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}.
+\]
+!et
+
+
+!split
+===== Program example for gradient descent with Ridge Regression =====
+!bc pycod
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+XT_X = xb.T @ xb
+
+#Ridge parameter lambda
+lmbda = 0.001
+Id = lmbda* np.eye(XT_X.shape[0])
+
+beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y
+print(beta_linreg)
+# Start plain gradient descent
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 100
+
+for iter in range(Niterations):
+ gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta
+ beta -= eta*gradients
+
+print(beta)
+ypredict = xb @ beta
+ypredict2 = xb @ beta_linreg
+plt.plot(x, ypredict, "r-")
+plt.plot(x, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example for Ridge')
+plt.show()
+
+
+!ec
+
+!split
+===== Using gradient descent methods, limitations =====
+
+* _Gradient descent (GD) finds local minima of our function_. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
+
+* _GD is sensitive to initial conditions_. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
+
+* _Gradients are computationally expensive to calculate for large datasets_. In many cases in statistics and ML, the energy function is a sum of terms, with one term for each data point. For example, in linear regression, $E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called ``mini batches''. This has the added benefit of introducing stochasticity into our algorithm.
+
+* _GD is very sensitive to choices of learning rates_. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.
+
+* _GD treats all directions in parameter space uniformly._ Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
+
+* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
+
+
+!split
+===== Friday September 25 =====
+
+
+!split
+===== Stochastic Gradient Descent =====
+
+Stochastic gradient descent (SGD) and variants thereof address some of
+the shortcomings of the Gradient descent method discussed above.
+
+The underlying idea of SGD comes from the observation that the cost
+function, which we want to minimize, can almost always be written as a
+sum over $n$ data points $\{\mathbf{x}_i\}_{i=1}^n$,
+!bt
+\[
+C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i,
+\mathbf{\beta}).
+\]
+!et
+
+!split
+===== Computation of gradients =====
+
+This in turn means that the gradient can be
+computed as a sum over $i$-gradients
+!bt
+\[
+\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i,
+\mathbf{\beta}).
+\]
+!et
+
+Stochasticity/randomness is introduced by only taking the
+gradient on a subset of the data called minibatches. If there are $n$
+data points and the size of each minibatch is $M$, there will be $n/M$
+minibatches. We denote these minibatches by $B_k$ where
+$k=1,\cdots,n/M$.
+
+!split
+===== SGD example =====
+As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$
+and we choose to have $M=5$ minibathces,
+then each minibatch contains two data points. In particular we have
+$B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 =
+(\mathbf{x}_9,\mathbf{x}_{10})$. Note that if you choose $M=1$ you
+have only a single batch with all data points and on the other extreme,
+you may choose $M=n$ resulting in a minibatch for each datapoint, i.e
+$B_k = \mathbf{x}_k$.
+
+The idea is now to approximate the gradient by replacing the sum over
+all data points with a sum over the data points in one the minibatches
+picked at random in each gradient descent step
+!bt
+\[
+\nabla_{\beta}
+C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i,
+\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta
+c_i(\mathbf{x}_i, \mathbf{\beta}).
+\]
+!et
+
+!split
+===== The gradient step =====
+
+Thus a gradient descent step now looks like
+!bt
+\[
+\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i,
+\mathbf{\beta})
+\]
+!et
+
+where $k$ is picked at random with equal
+probability from $[1,n/M]$. An iteration over the number of
+minibathces (n/M) is commonly referred to as an epoch. Thus it is
+typical to choose a number of epochs and for each epoch iterate over
+the number of minibatches, as exemplified in the code below.
+
+!split
+===== Simple example code =====
+
+!bc pycod
+import numpy as np
+
+n = 100 #100 datapoints
+M = 5 #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 10 #number of epochs
+
+j = 0
+for epoch in range(1,n_epochs+1):
+ for i in range(m):
+ k = np.random.randint(m) #Pick the k-th minibatch at random
+ #Compute the gradient using the data in minibatch Bk
+ #Compute new suggestion for
+ j += 1
+!ec
+
+Taking the gradient only on a subset of the data has two important
+benefits. First, it introduces randomness which decreases the chance
+that our opmization scheme gets stuck in a local minima. Second, if
+the size of the minibatches are small relative to the number of
+datapoints ($M < n$), the computation of the gradient is much
+cheaper since we sum over the datapoints in the $k-th$ minibatch and not
+all $n$ datapoints.
+
+!split
+===== When do we stop? =====
+
+A natural question is when do we stop the search for a new minimum?
+One possibility is to compute the full gradient after a given number
+of epochs and check if the norm of the gradient is smaller than some
+threshold and stop if true. However, the condition that the gradient
+is zero is valid also for local minima, so this would only tell us
+that we are close to a local/global minimum. However, we could also
+evaluate the cost function at this point, store the result and
+continue the search. If the test kicks in at a later stage we can
+compare the values of the cost function and keep the $\beta$ that
+gave the lowest value.
+
+!split
+===== Slightly different approach =====
+
+Another approach is to let the step length $\gamma_j$ depend on the
+number of epochs in such a way that it becomes very small after a
+reasonable time such that we do not move at all.
+
+As an example, let $e = 0,1,2,3,\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \cdot m + i$ where $m$ is the number of minibatches and $i=0,\cdots,m-1$. Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.
+
+In this way we can fix the number of epochs, compute $\beta$ and
+evaluate the cost function at the end. Repeating the computation will
+give a different result since the scheme is random by design. Then we
+pick the final $\beta$ that gives the lowest value of the cost
+function.
+
+!bc pycod
+import numpy as np
+
+def step_length(t,t0,t1):
+ return t0/(t+t1)
+
+n = 100 #100 datapoints
+M = 5 #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 500 #number of epochs
+t0 = 1.0
+t1 = 10
+
+gamma_j = t0/t1
+j = 0
+for epoch in range(1,n_epochs+1):
+ for i in range(m):
+ k = np.random.randint(m) #Pick the k-th minibatch at random
+ #Compute the gradient using the data in minibatch Bk
+ #Compute new suggestion for beta
+ t = epoch*m+i
+ gamma_j = step_length(t,t0,t1)
+ j += 1
+
+print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
+!ec
+
+
+
+
+
+!split
+===== Program for stochastic gradient =====
+
+!bc pycod
+# Importing various packages
+from math import exp, sqrt
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print("Own inversion")
+print(theta_linreg)
+sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print("sgdreg from scikit")
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+theta = np.random.randn(2,1)
+eta = 0.1
+Niterations = 1000
+
+
+for iter in range(Niterations):
+ gradients = 2.0/m*xb.T @ ((xb @ theta)-y)
+ theta -= eta*gradients
+print("theta frm own gd")
+print(theta)
+
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(theta)
+ypredict2 = xbnew.dot(theta_linreg)
+
+
+n_epochs = 50
+t0, t1 = 5, 50
+def learning_schedule(t):
+ return t0/(t+t1)
+
+theta = np.random.randn(2,1)
+
+for epoch in range(n_epochs):
+ for i in range(m):
+ random_index = np.random.randint(m)
+ xi = xb[random_index:random_index+1]
+ yi = y[random_index:random_index+1]
+ gradients = 2 * xi.T @ ((xi @ theta)-yi)
+ eta = learning_schedule(epoch*m+i)
+ theta = theta - eta*gradients
+print("theta from own sdg")
+print(theta)
+
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Random numbers ')
+plt.show()
+
+!ec
+
+_Challenge_: try to write a similar code for a Logistic Regression case.
+
+
+!split
+===== Momentum based GD =====
+
+The stochastic gradient descent (SGD) is almost always used with a
+*momentum* or inertia term that serves as a memory of the direction we
+are moving in parameter space. This is typically implemented as
+follows
+
+!bt
+\begin{align}
+\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\
+\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t},
+\end{align}
+!et
+
+where we have introduced a momentum parameter $\gamma$, with
+$0\le\gamma\le 1$, and for brevity we dropped the explicit notation to
+indicate the gradient is to be taken over a different mini-batch at
+each step. We call this algorithm gradient descent with momentum
+(GDM). From these equations, it is clear that $\mathbf{v}_t$ is a
+running average of recently encountered gradients and
+$(1-\gamma)^{-1}$ sets the characteristic time scale for the memory
+used in the averaging procedure. Consistent with this, when
+$\gamma=0$, this just reduces down to ordinary SGD as discussed
+earlier. An equivalent way of writing the updates is
+
+!bt
+\[
+\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t),
+\]
+!et
+where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$.
+
+!split
+===== More on momentum based approaches =====
+
+Let us try to get more intuition from these equations. It is helpful
+to consider a simple physical analogy with a particle of mass $m$
+moving in a viscous medium with drag coefficient $\mu$ and potential
+$E(\mathbf{w})$. If we denote the particle's position by $\mathbf{w}$,
+then its motion is described by
+
+!bt
+\[
+m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}).
+\]
+!et
+
+We can discretize this equation in the usual way to get
+
+!bt
+\[
+m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}).
+\]
+!et
+
+Rearranging this equation, we can rewrite this as
+
+!bt
+\[
+\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t.
+\]
+!et
+
+!split
+===== Momentum parameter =====
+
+Notice that this equation is identical to previous one if we identify
+the position of the particle, $\mathbf{w}$, with the parameters
+$\boldsymbol{\theta}$. This allows us to identify the momentum
+parameter and learning rate with the mass of the particle and the
+viscous drag as:
+
+!bt
+\[
+\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}.
+\]
+!et
+
+Thus, as the name suggests, the momentum parameter is proportional to
+the mass of the particle and effectively provides inertia.
+Furthermore, in the large viscosity/small learning rate limit, our
+memory time scales as $(1-\gamma)^{-1} \approx m/(\mu \Delta t)$.
+
+Why is momentum useful? SGD momentum helps the gradient descent
+algorithm gain speed in directions with persistent but small gradients
+even in the presence of stochasticity, while suppressing oscillations
+in high-curvature directions. This becomes especially important in
+situations where the landscape is shallow and flat in some directions
+and narrow and steep in others. It has been argued that first-order
+methods (with appropriate initial conditions) can perform comparable
+to more expensive second order methods, especially in the context of
+complex deep learning models.
+
+These beneficial properties of momentum can sometimes become even more
+pronounced by using a slight modification of the classical momentum
+algorithm called Nesterov Accelerated Gradient (NAG).
+
+In the NAG algorithm, rather than calculating the gradient at the
+current parameters, $\nabla_\theta E(\boldsymbol{\theta}_t)$, one
+calculates the gradient at the expected value of the parameters given
+our current momentum, $\nabla_\theta E(\boldsymbol{\theta}_t +\gamma
+\mathbf{v}_{t-1})$. This yields the NAG update rule
+
+!bt
+\begin{align}
+\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\
+\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}.
+\end{align}
+!et
+
+One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\gamma$.
+
+
+!split
+===== Second moment of the gradient =====
+
+
+In stochastic gradient descent, with and without momentum, we still
+have to specify a schedule for tuning the learning rates $\eta_t$
+as a function of time. As discussed in the context of Newton's
+method, this presents a number of dilemmas. The learning rate is
+limited by the steepest direction which can change depending on the
+current position in the landscape. To circumvent this problem, ideally
+our algorithm would keep track of curvature and take large steps in
+shallow, flat directions and small steps in steep, narrow directions.
+Second-order methods accomplish this by calculating or approximating
+the Hessian and normalizing the learning rate by the
+curvature. However, this is very computationally expensive for
+extremely large models. Ideally, we would like to be able to
+adaptively change the step size to match the landscape without paying
+the steep computational price of calculating or approximating
+Hessians.
+
+Recently, a number of methods have been introduced that accomplish
+this by tracking not only the gradient, but also the second moment of
+the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
+ADAM.
+
+!split
+===== RMS prop =====
+
+In RMS prop, in addition to keeping a running average of the first
+moment of the gradient, we also keep track of the second moment
+denoted by $\mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2]$. The update rule
+for RMS prop is given by
+
+!bt
+\begin{align}
+\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\
+\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\
+\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber
+\end{align}
+!et
+
+where $\beta$ controls the averaging time of the second moment and is
+typically taken to be about $\beta=0.9$, $\eta_t$ is a learning rate
+typically chosen to be $10^{-3}$, and $\epsilon\sim 10^{-8} $ is a
+small regularization constant to prevent divergences. Multiplication
+and division by vectors is understood as an element-wise operation. It
+is clear from this formula that the learning rate is reduced in
+directions where the norm of the gradient is consistently large. This
+greatly speeds up the convergence by allowing us to use a larger
+learning rate for flat directions.
+
+
+!split
+===== ADAM optimizer =====
+
+A related algorithm is the ADAM optimizer. In ADAM, we keep a running
+average of both the first and second moment of the gradient and use
+this information to adaptively change the learning rate for different
+parameters. In addition to keeping a running average of the first and
+second moments of the gradient
+(i.e. $\mathbf{m}_t=\mathbb{E}[\mathbf{g}_t]$ and
+$\mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t]$, respectively), ADAM
+performs an additional bias correction to account for the fact that we
+are estimating the first two moments of the gradient using a running
+average (denoted by the hats in the update rule below). The update
+rule for ADAM is given by (where multiplication and division are once
+again understood to be element-wise operations below)
+
+!bt
+\begin{align}
+\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) \\
+\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\
+\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\
+\hat{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\
+\hat{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\
+\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \hat{\mathbf{m}}_t \over \sqrt{\hat{\mathbf{s}}_t} +\epsilon}, \nonumber \\
+\end{align}
+!et
+
+where $\beta_1$ and $\beta_2$ set the memory lifetime of the first and
+second moment and are typically taken to be $0.9$ and $0.99$
+respectively, and $\eta$ and $\epsilon$ are identical to RMSprop.
+
+Like in RMSprop, the effective step size of a parameter depends on the
+magnitude of its gradient squared. To understand this better, let us
+rewrite this expression in terms of the variance
+$\boldsymbol{\sigma}_t^2 = \hat{\mathbf{s}}_t -
+(\hat{\mathbf{m}}_t)^2$. Consider a single parameter $\theta_t$. The
+update rule for this parameter is given by
+
+!bt
+\[
+\Delta \theta_{t+1}= -\eta_t { \hat{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}.
+\]
+!et
+
+
+
+
+!split
+===== Practical tips =====
+
+* _Randomize the data when making mini-batches_. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
+
+* _Transform your inputs_. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the energy matrix is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
+
+* _Monitor the out-of-sample performance._ Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.
+
+* _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
+
+Geron's text, see chapter 11, has several interesting discussions.
+
+
+
+!split
+===== Automatic differentiation =====
+
+"Automatic differentiation (AD)":"https://en.wikipedia.org/wiki/Automatic_differentiation",
+also called algorithmic
+differentiation or computational differentiation,is a set of
+techniques to numerically evaluate the derivative of a function
+specified by a computer program. AD exploits the fact that every
+computer program, no matter how complicated, executes a sequence of
+elementary arithmetic operations (addition, subtraction,
+multiplication, division, etc.) and elementary functions (exp, log,
+sin, cos, etc.). By applying the chain rule repeatedly to these
+operations, derivatives of arbitrary order can be computed
+automatically, accurately to working precision, and using at most a
+small constant factor more arithmetic operations than the original
+program.
+
+Automatic differentiation is neither:
+
+* Symbolic differentiation, nor
+* Numerical differentiation (the method of finite differences).
+
+Symbolic differentiation can lead to inefficient code and faces the
+difficulty of converting a computer program into a single expression,
+while numerical differentiation can introduce round-off errors in the
+discretization process and cancellation
+
+
+
+Python has tools for so-called _automatic differentiation_.
+Consider the following example
+!bt
+\[
+f(x) = \sin\left(2\pi x + x^2\right)
+\]
+!et
+which has the following derivative
+!bt
+\[
+f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
+\]
+!et
+Using _autograd_ we have
+
+!bc pycod
+import autograd.numpy as np
+
+# To do elementwise differentiation:
+from autograd import elementwise_grad as egrad
+
+# To plot:
+import matplotlib.pyplot as plt
+
+
+def f(x):
+ return np.sin(2*np.pi*x + x**2)
+
+def f_grad_analytic(x):
+ return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
+
+# Do the comparison:
+x = np.linspace(0,1,1000)
+
+f_grad = egrad(f)
+
+computed = f_grad(x)
+analytic = f_grad_analytic(x)
+
+plt.title('Derivative computed from Autograd compared with the analytical derivative')
+plt.plot(x,computed,label='autograd')
+plt.plot(x,analytic,label='analytic')
+
+plt.xlabel('x')
+plt.ylabel('y')
+plt.legend()
+
+plt.show()
+
+print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
+!ec
+
+!split
+===== Using autograd =====
+
+Here we
+experiment with what kind of functions Autograd is capable
+of finding the gradient of. The following Python functions are just
+meant to illustrate what Autograd can do, but please feel free to
+experiment with other, possibly more complicated, functions as well.
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+
+def f1(x):
+ return x**3 + 1
+
+f1_grad = grad(f1)
+
+# Remember to send in float as argument to the computed gradient from Autograd!
+a = 1.0
+
+# See the evaluated gradient at a using autograd:
+print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
+
+# Compare with the analytical derivative, that is f1'(x) = 3*x**2
+grad_analytical = 3*a**2
+print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
+!ec
+
+
+!split
+===== Autograd with more complicated functions =====
+
+To differentiate with respect to two (or more) arguments of a Python
+function, Autograd need to know at which variable the function if
+being differentiated with respect to.
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f2(x1,x2):
+ return 3*x1**3 + x2*(x1 - 5) + 1
+
+# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
+f2_grad_x1 = grad(f2,0)
+
+# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
+f2_grad_x2 = grad(f2,1)
+
+x1 = 1.0
+x2 = 3.0
+
+print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
+print("-"*30)
+
+# Compare with the analytical derivatives:
+
+# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
+f2_grad_x1_analytical = 9*x1**2 + x2
+
+# Derivative of f2 w.r.t x2 is: x1 - 5:
+f2_grad_x2_analytical = x1 - 5
+
+# See the evaluated derivations:
+print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+
+print()
+
+print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+!ec
+
+Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
+
+
+!split
+===== More complicated functions using the elements of their arguments directly =====
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f3(x): # Assumes x is an array of length 5 or higher
+ return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
+
+f3_grad = grad(f3)
+
+x = np.linspace(0,4,5)
+
+# Print the computed gradient:
+print("The computed gradient of f3 is: ", f3_grad(x))
+
+# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
+f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
+
+# Print the analytical gradient:
+print("The analytical gradient of f3 is: ", f3_grad_analytical)
+!ec
+
+Note that in this case, when sending an array as input argument, the
+output from Autograd is another array. This is the true gradient of
+the function, as opposed to the function in the previous example. By
+using arrays to represent the variables, the output from Autograd
+might be easier to work with, as the output is closer to what one
+could expect form a gradient-evaluting function.
+
+!split
+===== Functions using mathematical functions from Numpy =====
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f4(x):
+ return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
+
+f4_grad = grad(f4)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
+
+# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
+f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
+
+# Print the analytical gradient:
+print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
+!ec
+
+
+!split
+===== More autograd =====
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f5(x):
+ if x >= 0:
+ return x**2
+ else:
+ return -3*x + 1
+
+f5_grad = grad(f5)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
+!ec
+
+
+!split
+===== And with loops =====
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f6_for(x):
+ val = 0
+ for i in range(10):
+ val = val + x**i
+ return val
+
+def f6_while(x):
+ val = 0
+ i = 0
+ while i < 10:
+ val = val + x**i
+ i = i + 1
+ return val
+
+f6_for_grad = grad(f6_for)
+f6_while_grad = grad(f6_while)
+
+x = 0.5
+
+# Print the computed derivaties of f6_for and f6_while
+print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
+print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
+!ec
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
+# The analytical derivative is: sum(i*x**(i-1))
+f6_grad_analytical = 0
+for i in range(10):
+ f6_grad_analytical += i*x**(i-1)
+
+print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
+!ec
+
+!split
+===== Using recursion =====
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+
+def f7(n): # Assume that n is an integer
+ if n == 1 or n == 0:
+ return 1
+ else:
+ return n*f7(n-1)
+
+f7_grad = grad(f7)
+
+n = 2.0
+
+print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
+
+# The function f7 is an implementation of the factorial of n.
+# By using the product rule, one can find that the derivative is:
+
+f7_grad_analytical = 0
+for i in range(int(n)-1):
+ tmp = 1
+ for k in range(int(n)-1):
+ if k != i:
+ tmp *= (n - k)
+ f7_grad_analytical += tmp
+
+print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
+
+!ec
+Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
+
+!split
+===== Unsupported functions =====
+Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
+
+Assigning a value to the variable being differentiated with respect to
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f8(x): # Assume x is an array
+ x[2] = 3
+ return x*2
+
+f8_grad = grad(f8)
+
+x = 8.4
+
+print("The derivative of f8 is:",f8_grad(x))
+!ec
+Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
+
+!split
+===== The syntax a.dot(b) when finding the dot product =====
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f9(a): # Assume a is an array with 2 elements
+ b = np.array([1.0,2.0])
+ return a.dot(b)
+
+f9_grad = grad(f9)
+
+x = np.array([1.0,0.0])
+
+print("The derivative of f9 is:",f9_grad(x))
+!ec
+
+Here we are told that the 'dot' function does not belong to Autograd's
+version of a Numpy array. To overcome this, an alternative syntax
+which also computed the dot product can be used:
+
+!bc pycod
+import autograd.numpy as np
+from autograd import grad
+def f9_alternative(x): # Assume a is an array with 2 elements
+ b = np.array([1.0,2.0])
+ return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
+
+f9_alternative_grad = grad(f9_alternative)
+
+x = np.array([3.0,0.0])
+
+print("The gradient of f9 is:",f9_alternative_grad(x))
+
+# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
+# w.r.t x is (b_1, b_2).
+!ec
+
+!split
+===== Recommended to avoid =====
+The documentation recommends to avoid inplace operations such as
+!bc pycod
+a += b
+a -= b
+a*= b
+a /=b
+!ec
+
+
+!split
+===== Standard steepest descent =====
+
+
+Before we proceed, we would like to discuss the approach called the
+_standard Steepest descent_, which again leads to us having to be able
+to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).
+
+"The success of the CG method":"https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf"
+for finding solutions of non-linear problems is based on the theory
+of conjugate gradients for linear systems of equations. It belongs to
+the class of iterative methods for solving problems from linear
+algebra of the type
+!bt
+\begin{equation*}
+\hat{A}\hat{x} = \hat{b}.
+\end{equation*}
+!et
+
+In the iterative process we end up with a problem like
+
+!bt
+\begin{equation*}
+ \hat{r}= \hat{b}-\hat{A}\hat{x},
+\end{equation*}
+!et
+where $\hat{r}$ is the so-called residual or error in the iterative process.
+
+When we have found the exact solution, $\hat{r}=0$.
+
+!split
+===== Gradient method =====
+
+The residual is zero when we reach the minimum of the quadratic equation
+!bt
+\begin{equation*}
+ P(\hat{x})=\frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T\hat{b},
+\end{equation*}
+!et
+
+with the constraint that the matrix $\hat{A}$ is positive definite and
+symmetric. This defines also the Hessian and we want it to be positive definite.
+
+
+!split
+===== Steepest descent method =====
+
+We denote the initial guess for $\hat{x}$ as $\hat{x}_0$.
+We can assume without loss of generality that
+!bt
+\begin{equation*}
+\hat{x}_0=0,
+\end{equation*}
+!et
+or consider the system
+!bt
+\begin{equation*}
+\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0,
+\end{equation*}
+!et
+instead.
+
+
+!split
+===== Steepest descent method =====
+!bblock
+One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form
+!bt
+\begin{equation*}
+ f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n.
+\end{equation*}
+!et
+This suggests taking the first basis vector $\hat{r}_1$ (see below for definition)
+to be the gradient of $f$ at $\hat{x}=\hat{x}_0$,
+which equals
+!bt
+\begin{equation*}
+\hat{A}\hat{x}_0-\hat{b},
+\end{equation*}
+!et
+and
+$\hat{x}_0=0$ it is equal $-\hat{b}$.
+
+!eblock
+
+!split
+===== Final expressions =====
+!bblock
+We can compute the residual iteratively as
+!bt
+\begin{equation*}
+\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1},
+ \end{equation*}
+!et
+which equals
+!bt
+\begin{equation*}
+\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{r}_k),
+ \end{equation*}
+!et
+or
+!bt
+\begin{equation*}
+(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{r}_k,
+ \end{equation*}
+!et
+which gives
+
+!bt
+\[
+\alpha_k = \frac{\hat{r}_k^T\hat{r}_k}{\hat{r}_k^T\hat{A}\hat{r}_k}
+\]
+!et
+leading to the iterative scheme
+!bt
+\begin{equation*}
+\hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k},
+ \end{equation*}
+!et
+!eblock
+
+
+!split
+===== Code examples for steepest descent =====
+
+!split
+===== Simple codes for steepest descent and conjugate gradient using a $2\times 2$ matrix, in c++, Python code to come =====
+!bblock
+!bc cppcod
+#include
+#include
+#include
+#include
+#include "vectormatrixclass.h"
+using namespace std;
+// Main function begins here
+int main(int argc, char * argv[]){
+ int dim = 2;
+ Vector x(dim),xsd(dim), b(dim),x0(dim);
+ Matrix A(dim,dim);
+
+ // Set our initial guess
+ x0(0) = x0(1) = 0;
+ // Set the matrix
+ A(0,0) = 3; A(1,0) = 2; A(0,1) = 2; A(1,1) = 6;
+ b(0) = 2; b(1) = -8;
+ cout << "The Matrix A that we are using: " << endl;
+ A.Print();
+ cout << endl;
+ xsd = SteepestDescent(A,b,x0);
+ cout << "The approximate solution using Steepest Descent is: " << endl;
+ xsd.Print();
+ cout << endl;
+}
+!ec
+!eblock
+
+!split
+===== The routine for the steepest descent method =====
+!bblock
+!bc cppcod
+Vector SteepestDescent(Matrix A, Vector b, Vector x0){
+ int IterMax, i;
+ int dim = x0.Dimension();
+ const double tolerance = 1.0e-14;
+ Vector x(dim),f(dim),z(dim);
+ double c,alpha,d;
+ IterMax = 30;
+ x = x0;
+ r = A*x-b;
+ i = 0;
+ while (i <= IterMax){
+ z = A*r;
+ c = dot(r,r);
+ alpha = c/dot(r,z);
+ x = x - alpha*r;
+ r = A*x-b;
+ if(sqrt(dot(r,r)) < tolerance) break;
+ i++;
+ }
+ return x;
+}
+!ec
+!eblock
+
+
+!split
+===== Steepest descent example =====
+
+!bc pycod
+import numpy as np
+import numpy.linalg as la
+
+import scipy.optimize as sopt
+
+import matplotlib.pyplot as pt
+from mpl_toolkits.mplot3d import axes3d
+
+def f(x):
+ return 0.5*x[0]**2 + 2.5*x[1]**2
+
+def df(x):
+ return np.array([x[0], 5*x[1]])
+
+fig = pt.figure()
+ax = fig.gca(projection="3d")
+
+xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
+fmesh = f(np.array([xmesh, ymesh]))
+ax.plot_surface(xmesh, ymesh, fmesh)
+!ec
+And then as countor plot
+!bc pycod
+pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh)
+guesses = [np.array([2, 2./5])]
+!ec
+Find guesses
+!bc pycod
+x = guesses[-1]
+s = -df(x)
+!ec
+Run it!
+!bc pycod
+def f1d(alpha):
+ return f(x + alpha*s)
+
+alpha_opt = sopt.golden(f1d)
+next_guess = x + alpha_opt * s
+guesses.append(next_guess)
+print(next_guess)
+!ec
+What happened?
+!bc pycod
+pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh, 50)
+it_array = np.array(guesses)
+pt.plot(it_array.T[0], it_array.T[1], "x-")
+!ec
+
+!split
+===== Conjugate gradient method =====
+!bblock
+In the CG method we define so-called conjugate directions and two vectors
+$\hat{s}$ and $\hat{t}$
+are said to be
+conjugate if
+!bt
+\begin{equation*}
+\hat{s}^T\hat{A}\hat{t}= 0.
+\end{equation*}
+!et
+The philosophy of the CG method is to perform searches in various conjugate directions
+of our vectors $\hat{x}_i$ obeying the above criterion, namely
+!bt
+\begin{equation*}
+\hat{x}_i^T\hat{A}\hat{x}_j= 0.
+\end{equation*}
+!et
+Two vectors are conjugate if they are orthogonal with respect to
+this inner product. Being conjugate is a symmetric relation: if $\hat{s}$ is conjugate to $\hat{t}$, then $\hat{t}$ is conjugate to $\hat{s}$.
+!eblock
+
+!split
+===== Conjugate gradient method =====
+!bblock
+An example is given by the eigenvectors of the matrix
+!bt
+\begin{equation*}
+\hat{v}_i^T\hat{A}\hat{v}_j= \lambda\hat{v}_i^T\hat{v}_j,
+\end{equation*}
+!et
+which is zero unless $i=j$.
+!eblock
+
+
+!split
+===== Conjugate gradient method =====
+!bblock
+Assume now that we have a symmetric positive-definite matrix $\hat{A}$ of size
+$n\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector
+!bt
+\begin{equation*}
+\hat{x}_{i+1}=\hat{x}_{i}+\alpha_i\hat{p}_{i}.
+\end{equation*}
+!et
+We assume that $\hat{p}_{i}$ is a sequence of $n$ mutually conjugate directions.
+Then the $\hat{p}_{i}$ form a basis of $R^n$ and we can expand the solution
+$ \hat{A}\hat{x} = \hat{b}$ in this basis, namely
+
+!bt
+\begin{equation*}
+ \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i.
+\end{equation*}
+!et
+!eblock
+
+!split
+===== Conjugate gradient method =====
+!bblock
+The coefficients are given by
+!bt
+\begin{equation*}
+ \mathbf{A}\mathbf{x} = \sum^{n}_{i=1} \alpha_i \mathbf{A} \mathbf{p}_i = \mathbf{b}.
+\end{equation*}
+!et
+Multiplying with $\hat{p}_k^T$ from the left gives
+
+!bt
+\begin{equation*}
+ \hat{p}_k^T \hat{A}\hat{x} = \sum^{n}_{i=1} \alpha_i\hat{p}_k^T \hat{A}\hat{p}_i= \hat{p}_k^T \hat{b},
+\end{equation*}
+!et
+and we can define the coefficients $\alpha_k$ as
+
+!bt
+\begin{equation*}
+ \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k}
+\end{equation*}
+!et
+!eblock
+
+!split
+===== Conjugate gradient method and iterations =====
+!bblock
+
+If we choose the conjugate vectors $\hat{p}_k$ carefully,
+then we may not need all of them to obtain a good approximation to the solution
+$\hat{x}$.
+We want to regard the conjugate gradient method as an iterative method.
+This will us to solve systems where $n$ is so large that the direct
+method would take too much time.
+
+We denote the initial guess for $\hat{x}$ as $\hat{x}_0$.
+We can assume without loss of generality that
+!bt
+\begin{equation*}
+\hat{x}_0=0,
+\end{equation*}
+!et
+or consider the system
+!bt
+\begin{equation*}
+\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0,
+\end{equation*}
+!et
+instead.
+!eblock
+
+
+!split
+===== Conjugate gradient method =====
+!bblock
+One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form
+!bt
+\begin{equation*}
+ f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n.
+\end{equation*}
+!et
+This suggests taking the first basis vector $\hat{p}_1$
+to be the gradient of $f$ at $\hat{x}=\hat{x}_0$,
+which equals
+!bt
+\begin{equation*}
+\hat{A}\hat{x}_0-\hat{b},
+\end{equation*}
+!et
+and
+$\hat{x}_0=0$ it is equal $-\hat{b}$.
+The other vectors in the basis will be conjugate to the gradient,
+hence the name conjugate gradient method.
+!eblock
+
+
+!split
+===== Conjugate gradient method =====
+!bblock
+Let $\hat{r}_k$ be the residual at the $k$-th step:
+!bt
+\begin{equation*}
+\hat{r}_k=\hat{b}-\hat{A}\hat{x}_k.
+\end{equation*}
+!et
+Note that $\hat{r}_k$ is the negative gradient of $f$ at
+$\hat{x}=\hat{x}_k$,
+so the gradient descent method would be to move in the direction $\hat{r}_k$.
+Here, we insist that the directions $\hat{p}_k$ are conjugate to each other,
+so we take the direction closest to the gradient $\hat{r}_k$
+under the conjugacy constraint.
+This gives the following expression
+!bt
+\begin{equation*}
+\hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k.
+\end{equation*}
+!et
+!eblock
+
+!split
+===== Conjugate gradient method =====
+!bblock
+We can also compute the residual iteratively as
+!bt
+\begin{equation*}
+\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1},
+ \end{equation*}
+!et
+which equals
+!bt
+\begin{equation*}
+\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{p}_k),
+ \end{equation*}
+!et
+or
+!bt
+\begin{equation*}
+(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{p}_k,
+ \end{equation*}
+!et
+which gives
+
+!bt
+\begin{equation*}
+\hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k},
+ \end{equation*}
+!et
+!eblock
+
+
+
+!split
+===== Simple implementation of the Conjugate gradient algorithm =====
+!bblock
+!bc cppcod
+ Vector ConjugateGradient(Matrix A, Vector b, Vector x0){
+ int dim = x0.Dimension();
+ const double tolerance = 1.0e-14;
+ Vector x(dim),r(dim),v(dim),z(dim);
+ double c,t,d;
+
+ x = x0;
+ r = b - A*x;
+ v = r;
+ c = dot(r,r);
+ int i = 0; IterMax = dim;
+ while(i <= IterMax){
+ z = A*v;
+ t = c/dot(v,z);
+ x = x + t*v;
+ r = r - t*z;
+ d = dot(r,r);
+ if(sqrt(d) < tolerance)
+ break;
+ v = r + (d/c)*v;
+ c = d; i++;
+ }
+ return x;
+}
+!ec
+!eblock
+
+
+!split
+===== Broyden–Fletcher–Goldfarb–Shanno algorithm =====
+!bblock
+The optimization problem is to minimize $f(\mathbf {x} )$ where $\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\mathbf {x}$ can take.
+
+The algorithm begins at an initial estimate for the optimal value $\mathbf {x}_{0}$ and proceeds iteratively to get a better estimate at each stage.
+
+The search direction $p_k$ at stage $k$ is given by the solution of the analogue of the Newton equation
+!bt
+\[
+B_{k}\mathbf {p} _{k}=-\nabla f(\mathbf {x}_{k}),
+\]
+!et
+
+where $B_{k}$ is an approximation to the Hessian matrix, which is
+updated iteratively at each stage, and $\nabla f(\mathbf {x} _{k})$
+is the gradient of the function
+evaluated at $x_k$.
+A line search in the direction $p_k$ is then used to
+find the next point $x_{k+1}$ by minimising
+!bt
+\[
+f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}),
+\]
+!et
+over the scalar $\alpha > 0$.
+
+!eblock
+
+
+
+
+
+
diff --git a/doc/src/week40/week40.do.txt b/doc/src/week40/week40.do.txt
new file mode 100644
index 000000000..75e2e36ef
--- /dev/null
+++ b/doc/src/week40/week40.do.txt
@@ -0,0 +1,2454 @@
+TITLE: Weeke 40: Neural networks, from the simple perceptron to deep 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
+
+
+
+!split
+===== Neural networks =====
+
+Artificial neural networks are computational systems that can learn to
+perform tasks by considering examples, generally without being
+programmed with any task-specific rules. It is supposed to mimic a
+biological system, wherein neurons interact by sending signals in the
+form of mathematical functions between layers. All layers can contain
+an arbitrary number of neurons, and each connection is represented by
+a weight variable.
+
+
+!split
+===== Artificial neurons =====
+
+The field of artificial neural networks has a long history of
+development, and is closely connected with the advancement of computer
+science and computers in general. A model of artificial neurons was
+first developed by McCulloch and Pitts in 1943 to study signal
+processing in the brain and has later been refined by others. The
+general idea is to mimic neural networks in the human brain, which is
+composed of billions of neurons that communicate with each other by
+sending electrical signals. Each neuron accumulates its incoming
+signals, which must exceed an activation threshold to yield an
+output. If the threshold is not overcome, the neuron remains inactive,
+i.e. has zero output.
+
+This behaviour has inspired a simple mathematical model for an artificial neuron.
+
+!bt
+\begin{equation}
+ y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u)
+ label{artificialNeuron}
+\end{equation}
+!et
+Here, the output $y$ of the neuron is the value of its activation function, which have as input
+a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons.
+
+Conceptually, it is helpful to divide neural networks into four
+categories:
+o general purpose neural networks for supervised learning,
+o neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),
+o neural networks for sequential data such as Recurrent Neural Networks (RNNs), and
+o neural networks for unsupervised learning such as Deep Boltzmann Machines.
+
+
+In natural science, DNNs and CNNs have already found numerous
+applications. In statistical physics, they have been applied to detect
+phase transitions in 2D Ising and Potts models, lattice gauge
+theories, and different phases of polymers, or solving the
+Navier-Stokes equation in weather forecasting. Deep learning has also
+found interesting applications in quantum physics. Various quantum
+phase transitions can be detected and studied using DNNs and CNNs,
+topological phases, and even non-equilibrium many-body
+localization. Representing quantum states as DNNs quantum state
+tomography are among some of the impressive achievements to reveal the
+potential of DNNs to facilitate the study of quantum systems.
+
+In quantum information theory, it has been shown that one can perform
+gate decompositions with the help of neural.
+
+The applications are not limited to the natural sciences. There is a
+plethora of applications in essentially all disciplines, from the
+humanities to life science and medicine.
+
+!split
+===== Neural network types =====
+
+An artificial neural network (ANN), is a computational model that
+consists of layers of connected neurons, or nodes or units. We will
+refer to these interchangeably as units or nodes, and sometimes as
+neurons.
+
+It is supposed to mimic a biological nervous system by letting each
+neuron interact with other neurons by sending signals in the form of
+mathematical functions between layers. A wide variety of different
+ANNs have been developed, but most of them consist of an input layer,
+an output layer and eventual layers in-between, called *hidden
+layers*. All layers can contain an arbitrary number of nodes, and each
+connection between two nodes is associated with a weight variable.
+
+Neural networks (also called neural nets) are neural-inspired
+nonlinear models for supervised learning. As we will see, neural nets
+can be viewed as natural, more powerful extensions of supervised
+learning methods such as linear and logistic regression and soft-max
+methods we discussed earlier.
+
+
+!split
+===== Feed-forward neural networks =====
+
+The feed-forward neural network (FFNN) was the first and simplest type
+of ANNs that were devised. In this network, the information moves in
+only one direction: forward through the layers.
+
+Nodes are represented by circles, while the arrows display the
+connections between the nodes, including the direction of information
+flow. Additionally, each arrow corresponds to a weight variable
+(figure to come). We observe that each node in a layer is connected
+to *all* nodes in the subsequent layer, making this a so-called
+*fully-connected* FFNN.
+
+
+
+!split
+===== Convolutional Neural Network =====
+
+A different variant of FFNNs are *convolutional neural networks*
+(CNNs), which have a connectivity pattern inspired by the animal
+visual cortex. Individual neurons in the visual cortex only respond to
+stimuli from small sub-regions of the visual field, called a receptive
+field. This makes the neurons well-suited to exploit the strong
+spatially local correlation present in natural images. The response of
+each neuron can be approximated mathematically as a convolution
+operation. (figure to come)
+
+Convolutional neural networks emulate the behaviour of neurons in the
+visual cortex by enforcing a *local* connectivity pattern between
+nodes of adjacent layers: Each node in a convolutional layer is
+connected only to a subset of the nodes in the previous layer, in
+contrast to the fully-connected FFNN. Often, CNNs consist of several
+convolutional layers that learn local features of the input, with a
+fully-connected layer at the end, which gathers all the local data and
+produces the outputs. They have wide applications in image and video
+recognition.
+
+!split
+===== Recurrent neural networks =====
+
+So far we have only mentioned ANNs where information flows in one
+direction: forward. *Recurrent neural networks* on the other hand,
+have connections between nodes that form directed *cycles*. This
+creates a form of internal memory which are able to capture
+information on what has been calculated before; the output is
+dependent on the previous computations. Recurrent NNs make use of
+sequential information by performing the same task for every element
+in a sequence, where each element depends on previous elements. An
+example of such information is sentences, making recurrent NNs
+especially well-suited for handwriting and speech recognition.
+
+!split
+===== Other types of networks =====
+
+There are many other kinds of ANNs that have been developed. One type
+that is specifically designed for interpolation in multidimensional
+space is the radial basis function (RBF) network. RBFs are typically
+made up of three layers: an input layer, a hidden layer with
+non-linear radial symmetric activation functions and a linear output
+layer (''linear'' here means that each node in the output layer has a
+linear activation function). The layers are normally fully-connected
+and there are no cycles, thus RBFs can be viewed as a type of
+fully-connected FFNN. They are however usually treated as a separate
+type of NN due the unusual activation functions.
+
+!split
+===== Multilayer perceptrons =====
+
+One uses often so-called fully-connected feed-forward neural networks
+with three or more layers (an input layer, one or more hidden layers
+and an output layer) consisting of neurons that have non-linear
+activation functions.
+
+Such networks are often called *multilayer perceptrons* (MLPs).
+
+!split
+===== Why multilayer perceptrons? =====
+
+According to the *Universal approximation theorem*, a feed-forward
+neural network with just a single hidden layer containing a finite
+number of neurons can approximate a continuous multidimensional
+function to arbitrary accuracy, assuming the activation function for
+the hidden layer is a _non-constant, bounded and
+monotonically-increasing continuous function_.
+
+Note that the requirements on the activation function only applies to
+the hidden layer, the output nodes are always assumed to be linear, so
+as to not restrict the range of output values.
+
+
+!split
+===== Mathematical model =====
+
+The output $y$ is produced via the activation function $f$
+!bt
+\[
+ y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z),
+\]
+!et
+This function receives $x_i$ as inputs.
+Here the activation $z=(\sum_{i=1}^n w_ix_i+b_i)$.
+In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of
+the neurons in the preceding layer. Furthermore, an MLP is
+fully-connected, which means that each neuron receives a weighted sum
+of the outputs of *all* neurons in the previous layer.
+
+!split
+===== Mathematical model =====
+
+First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$,
+
+!bt
+\begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1
+\end{equation}
+!et
+
+Here $b_i$ is the so-called bias which is normally needed in
+case of zero activation weights or inputs. How to fix the biases and
+the weights will be discussed below. The value of $z_i^1$ is the
+argument to the activation function $f_i$ of each node $i$, The
+variable $M$ stands for all possible inputs to a given node $i$ in the
+first layer. We define the output $y_i^1$ of all neurons in layer 1 as
+
+!bt
+\begin{equation}
+ y_i^1 = f(z_i^1) = f\left(\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\right)
+ label{outputLayer1}
+\end{equation}
+!et
+
+where we assume that all nodes in the same layer have identical
+activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.
+In this case we would identify these functions with a superscript $l$ for the $l$-th layer,
+
+!bt
+\begin{equation}
+ y_i^l = f^l(u_i^l) = f^l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right)
+ label{generalLayer}
+\end{equation}
+!et
+
+where $N_l$ is the number of nodes in layer $l$. When the output of
+all the nodes in the first hidden layer are computed, the values of
+the subsequent layer can be calculated and so forth until the output
+is obtained.
+
+
+
+!split
+===== Mathematical model =====
+
+The output of neuron $i$ in layer 2 is thus,
+
+!bt
+\begin{align}
+ y_i^2 &= f^2\left(\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\right) \\
+ &= f^2\left[\sum_{j=1}^N w_{ij}^2f^1\left(\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\right) + b_i^2\right]
+ label{outputLayer2}
+\end{align}
+!et
+where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads
+
+!bt
+\begin{align}
+ y_i^3 &= f^3\left(\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\right) \\
+ &= f_3\left[\sum_{j} w_{ij}^3 f^2\left(\sum_{k} w_{jk}^2 f^1\left(\sum_{m} w_{km}^1 x_m + b_k^1\right) + b_j^2\right)
+ + b_1^3\right]
+\end{align}
+!et
+
+!split
+===== Mathematical model =====
+
+We can generalize this expression to an MLP with $l$ hidden
+layers. The complete functional form is,
+
+!bt
+\begin{align}
+&y^{l+1}_i = f^{l+1}\left[\!\sum_{j=1}^{N_l} w_{ij}^3 f^l\left(\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\left(\dots f^1\left(\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\right)\dots\right)+b_k^2\right)+b_1^3\right] &&
+ label{completeNN}
+\end{align}
+!et
+
+which illustrates a basic property of MLPs: The only independent
+variables are the input values $x_n$.
+
+!split
+===== Mathematical model =====
+
+This confirms that an MLP, despite its quite convoluted mathematical
+form, is nothing more than an analytic function, specifically a
+mapping of real-valued vectors $\hat{x} \in \mathbb{R}^n \rightarrow
+\hat{y} \in \mathbb{R}^m$.
+
+Furthermore, the flexibility and universality of an MLP can be
+illustrated by realizing that the expression is essentially a nested
+sum of scaled activation functions of the form
+
+!bt
+\begin{equation}
+ f(x) = c_1 f(c_2 x + c_3) + c_4
+\end{equation}
+!et
+
+where the parameters $c_i$ are weights and biases. By adjusting these
+parameters, the activation functions can be shifted up and down or
+left and right, change slope or be rescaled which is the key to the
+flexibility of a neural network.
+
+!split
+=== Matrix-vector notation ===
+
+We can introduce a more convenient notation for the activations in an A NN.
+
+Additionally, we can represent the biases and activations
+as layer-wise column vectors $\hat{b}_l$ and $\hat{y}_l$, so that the $i$-th element of each vector
+is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively.
+
+We have that $\mathrm{W}_l$ is an $N_{l-1} \times N_l$ matrix, while $\hat{b}_l$ and $\hat{y}_l$ are $N_l \times 1$ column vectors.
+With this notation, the sum becomes a matrix-vector multiplication, and we can write
+the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as
+!bt
+\begin{equation}
+ \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) =
+ f_2\left(\left[\begin{array}{ccc}
+ w^2_{11} &w^2_{12} &w^2_{13} \\
+ w^2_{21} &w^2_{22} &w^2_{23} \\
+ w^2_{31} &w^2_{32} &w^2_{33} \\
+ \end{array} \right] \cdot
+ \left[\begin{array}{c}
+ y^1_1 \\
+ y^1_2 \\
+ y^1_3 \\
+ \end{array}\right] +
+ \left[\begin{array}{c}
+ b^2_1 \\
+ b^2_2 \\
+ b^2_3 \\
+ \end{array}\right]\right).
+\end{equation}
+!et
+
+!split
+=== Matrix-vector notation and activation ===
+
+The activation of node $i$ in layer 2 is
+
+!bt
+\begin{equation}
+ y^2_i = f_2\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\Bigr) =
+ f_2\left(\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\right).
+\end{equation}
+!et
+
+This is not just a convenient and compact notation, but also a useful
+and intuitive way to think about MLPs: The output is calculated by a
+series of matrix-vector multiplications and vector additions that are
+used as input to the activation functions. For each operation
+$\mathrm{W}_l \hat{y}_{l-1}$ we move forward one layer.
+
+
+!split
+=== Activation functions ===
+
+
+A property that characterizes a neural network, other than its
+connectivity, is the choice of activation function(s). As described
+in, the following restrictions are imposed on an activation function
+for a FFNN to fulfill the universal approximation theorem
+
+ * Non-constant
+
+ * Bounded
+
+ * Monotonically-increasing
+
+ * Continuous
+
+!split
+=== Activation functions, Logistic and Hyperbolic ones ===
+
+The second requirement excludes all linear functions. Furthermore, in
+a MLP with only linear activation functions, each layer simply
+performs a linear transformation of its inputs.
+
+Regardless of the number of layers, the output of the NN will be
+nothing but a linear function of the inputs. Thus we need to introduce
+some kind of non-linearity to the NN to be able to fit non-linear
+functions Typical examples are the logistic *Sigmoid*
+
+!bt
+\[
+ f(x) = \frac{1}{1 + e^{-x}},
+\]
+!et
+and the *hyperbolic tangent* function
+!bt
+\[
+ f(x) = \tanh(x)
+\]
+!et
+
+!split
+=== Relevance ===
+
+The *sigmoid* function are more biologically plausible because the
+output of inactive neurons are zero. Such activation function are
+called *one-sided*. However, it has been shown that the hyperbolic
+tangent performs better than the sigmoid for training MLPs. has
+become the most popular for *deep neural networks*
+
+!bc pycod
+"""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()
+
+"""Sine Function"""
+z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
+t = numpy.sin(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('sine function')
+
+plt.show()
+
+"""Plots a graph of the squashing function used by a rectified linear
+unit"""
+z = numpy.arange(-2, 2, .1)
+zero = numpy.zeros(len(z))
+y = numpy.max([zero, z], axis=0)
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+ax.plot(z, y)
+ax.set_ylim([-2.0, 2.0])
+ax.set_xlim([-2.0, 2.0])
+ax.grid(True)
+ax.set_xlabel('z')
+ax.set_title('Rectified linear unit')
+
+plt.show()
+!ec
+
+
+!split
+===== The multilayer perceptron (MLP) =====
+
+The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of
+o A neural network with one or more layers of nodes between the input and the output nodes.
+o The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.
+o The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.
+
+As a convention it is normal to call a network with one layer of input units, one layer of hidden
+units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.
+
+For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.
+Hereafter we will call the various entities of a layer for nodes.
+There are also no connections within a single layer.
+
+The number of input nodes does not need to equal the number of output
+nodes. This applies also to the hidden layers. Each layer may have its
+own number of nodes and activation functions.
+
+The hidden layers have their name from the fact that they are not
+linked to observables and as we will see below when we define the
+so-called activation $\hat{z}$, we can think of this as a basis
+expansion of the original inputs $\hat{x}$. The difference however
+between neural networks and say linear regression is that now these
+basis functions (which will correspond to the weights in the network)
+are learned from data. This results in an important difference between
+neural networks and deep learning approaches on one side and methods
+like logistic regression or linear regression and their modifications on the other side.
+
+
+!split
+===== From one to many layers, the universal approximation theorem =====
+
+
+A neural network with only one layer, what we called the simple
+perceptron, is best suited if we have a standard binary model with
+clear (linear) boundaries between the outcomes. As such it could
+equally well be replaced by standard linear regression or logistic
+regression. Networks with one or more hidden layers approximate
+systems with more complex boundaries.
+
+As stated earlier,
+an important theorem in studies of neural networks, restated without
+proof here, is the "universal approximation
+theorem":"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf".
+
+It states that a feed-forward network with a single hidden layer
+containing a finite number of neurons can approximate continuous
+functions on compact subsets of real functions. The theorem thus
+states that simple neural networks can represent a wide variety of
+interesting functions when given appropriate parameters. It is the
+multilayer feedforward architecture itself which gives neural networks
+the potential of being universal approximators.
+
+
+!split
+===== Deriving the back propagation code for a multilayer perceptron model =====
+
+
+_Note: figures will be inserted later!_
+
+As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.
+The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.
+This leads us to the famous "back propagation algorithm":"https://www.nature.com/articles/323533a0".
+
+The questions we want to ask are how do changes in the biases and the
+weights in our network change the cost function and how can we use the
+final output to modify the weights?
+
+To derive these equations let us start with a plain regression problem
+and define our cost function as
+
+!bt
+\[
+{\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2,
+\]
+!et
+
+where the $t_i$s are our $n$ targets (the values we want to
+reproduce), while the outputs of the network after having propagated
+all inputs $\hat{x}$ are given by $y_i$. Below we will demonstrate
+how the basic equations arising from the back propagation algorithm
+can be modified in order to study classification problems with $K$
+classes.
+
+!split
+===== Definitions =====
+
+With our definition of the targets $\hat{t}$, the outputs of the
+network $\hat{y}$ and the inputs $\hat{x}$ we
+define now the activation $z_j^l$ of node/neuron/unit $j$ of the
+$l$-th layer as a function of the bias, the weights which add up from
+the previous layer $l-1$ and the forward passes/outputs
+$\hat{a}^{l-1}$ from the previous layer as
+
+
+!bt
+\[
+z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,
+\]
+!et
+
+where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$
+represents the total number of nodes/neurons/units of layer $l-1$. The
+figure here illustrates this equation. We can rewrite this in a more
+compact form as the matrix-vector products we discussed earlier,
+
+!bt
+\[
+\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l.
+\]
+!et
+
+With the activation values $\hat{z}^l$ we can in turn define the
+output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our
+activation function. In the examples here we will use the sigmoid
+function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers
+and their nodes. It means we have
+
+!bt
+\[
+a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}.
+\]
+!et
+
+
+!split
+===== Derivatives and the chain rule =====
+
+From the definition of the activation $z_j^l$ we have
+!bt
+\[
+\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1},
+\]
+!et
+and
+!bt
+\[
+\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l.
+\]
+!et
+
+With our definition of the activation function we have that (note that this function depends only on $z_j^l$)
+!bt
+\[
+\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).
+\]
+!et
+
+
+!split
+===== Derivative of the cost function =====
+
+With these definitions we can now compute the derivative of the cost function in terms of the weights.
+
+Let us specialize to the output layer $l=L$. Our cost function is
+!bt
+\[
+{\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2,
+\]
+!et
+The derivative of this function with respect to the weights is
+
+!bt
+\[
+\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}},
+\]
+!et
+The last partial derivative can easily be computed and reads (by applying the chain rule)
+!bt
+\[
+\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},
+\]
+!et
+
+
+
+!split
+===== Bringing it together, first back propagation equation =====
+
+We have thus
+!bt
+\[
+\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1},
+\]
+!et
+
+Defining
+!bt
+\[
+\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)},
+\]
+!et
+and using the Hadamard product of two vectors we can write this as
+!bt
+\[
+\hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}^L)}.
+\]
+!et
+
+This is an important expression. The second term on the right handside
+measures how fast the cost function is changing as a function of the $j$th
+output activation. If, for example, the cost function doesn't depend
+much on a particular output node $j$, then $\delta_j^L$ will be small,
+which is what we would expect. The first term on the right, measures
+how fast the activation function $f$ is changing at a given activation
+value $z_j^L$.
+
+Notice that everything in the above equations is easily computed. In
+particular, we compute $z_j^L$ while computing the behaviour of the
+network, and it is only a small additional overhead to compute
+$f'(z^L_j)$. The exact form of the derivative with respect to the
+output depends on the form of the cost function.
+However, provided the cost function is known there should be little
+trouble in calculating
+
+!bt
+\[
+\frac{\partial {\cal C}}{\partial (a_j^L)}
+\]
+!et
+
+With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely
+!bt
+\[
+\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}.
+\]
+!et
+
+!split
+===== Derivatives in terms of $z_j^L$ =====
+
+It is also easy to see that our previous equation can be written as
+
+!bt
+\[
+\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L},
+\]
+!et
+which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely
+!bt
+\[
+\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L},
+\]
+!et
+That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias.
+!split
+===== Bringing it together =====
+
+We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are
+
+!bblock The starting equations
+
+!bt
+\begin{equation}
+\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1},
+\end{equation}
+!et
+and
+!bt
+\begin{equation}
+\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)},
+\end{equation}
+!et
+and
+
+!bt
+\begin{equation}
+\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L},
+\end{equation}
+!et
+!eblock
+
+
+An interesting consequence of the above equations is that when the
+activation $a_k^{L-1}$ is small, the gradient term, that is the
+derivative of the cost function with respect to the weights, will also
+tend to be small. We say then that the weight learns slowly, meaning
+that it changes slowly when we minimize the weights via say gradient
+descent. In this case we say the system learns slowly.
+
+Another interesting feature is that is when the activation function,
+represented by the sigmoid function here, is rather flat when we move towards
+its end values $0$ and $1$ (see the above Python codes). In these
+cases, the derivatives of the activation function will also be close
+to zero, meaning again that the gradients will be small and the
+network learns slowly again.
+
+
+
+We need a fourth equation and we are set. We are going to propagate
+backwards in order to the determine the weights and biases. In order
+to do so we need to represent the error in the layer before the final
+one $L-1$ in terms of the errors in the final output layer.
+
+!split
+===== Final back propagating equation =====
+
+We have that (replacing $L$ with a general layer $l$)
+!bt
+\[
+\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}.
+\]
+!et
+We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have
+
+!bt
+\[
+\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}},
+\]
+!et
+and recalling that
+!bt
+\[
+z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},
+\]
+!et
+with $M_l$ being the number of nodes in layer $l$, we obtain
+!bt
+\[
+\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),
+\]
+!et
+This is our final equation.
+
+We are now ready to set up the algorithm for back propagation and learning the weights and biases.
+
+!split
+===== Setting up the Back propagation algorithm =====
+
+
+
+The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.
+
+!bblock
+First, we set up the input data $\hat{x}$ and the activations
+$\hat{z}_1$ of the input layer and compute the activation function and
+the pertinent outputs $\hat{a}^1$.
+!eblock
+
+!bblock
+Secondly, we perform then the feed forward till we reach the output
+layer and compute all $\hat{z}_l$ of the input layer and compute the
+activation function and the pertinent outputs $\hat{a}^l$ for
+$l=2,3,\dots,L$.
+!eblock
+
+!bblock
+Thereafter we compute the ouput error $\hat{\delta}^L$ by computing all
+!bt
+\[
+\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}.
+\]
+!et
+!eblock
+
+!bblock
+Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as
+!bt
+\[
+\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).
+\]
+!et
+!eblock
+
+!bblock
+Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,2$ and update the weights and biases according to the rules
+!bt
+\[
+w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1},
+\]
+!et
+
+!bt
+\[
+b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
+\]
+!et
+!eblock
+
+The parameter $\eta$ is the learning parameter discussed in connection with the gradient descent methods.
+Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training.
+
+
+!split
+===== Setting up a Multi-layer perceptron model for classification =====
+
+We are now gong to develop an example based on the MNIST data
+base. This is a classification problem and we need to use our
+cross-entropy function we discussed in connection with logistic
+regression. The cross-entropy defines our cost function for the
+classificaton problems with neural networks.
+
+In binary classification with two classes $(0, 1)$ we define the
+logistic/sigmoid function as the probability that a particular input
+is in class $0$ or $1$. This is possible because the logistic
+function takes any input from the real numbers and inputs a number
+between 0 and 1, and can therefore be interpreted as a probability. It
+also has other nice properties, such as a derivative that is simple to
+calculate.
+
+For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$
+is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$
+represents our activation values $z$. We have
+!bt
+\[
+P(y = 0 \mid \hat{x}, \hat{\theta}) = \frac{1}{1 + \exp{(- \hat{x}})} ,
+\]
+!et
+and
+!bt
+\[
+P(y = 1 \mid \hat{x}, \hat{\theta}) = 1 - P(y = 0 \mid \hat{x}, \hat{\theta}) ,
+\]
+!et
+
+where $y \in \{0, 1\}$ and $\hat{\theta}$ represents the weights and biases
+of our network.
+
+
+!split
+===== Defining the cost function =====
+
+Our cost function is given as (see the Logistic regression lectures)
+!bt
+\[
+\mathcal{C}(\hat{\theta}) = - \ln P(\mathcal{D} \mid \hat{\theta}) = - \sum_{i=1}^n
+y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\hat{\theta}) .
+\]
+!et
+
+This last equality means that we can interpret our *cost* function as a sum over the *loss* function
+for each point in the dataset $\mathcal{L}_i(\hat{\theta})$.
+The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather
+than maximizing a negative number.
+
+In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector:
+
+$y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and
+
+
+$y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$
+
+
+i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$)..
+
+If $\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th
+output vector $\hat{y}_i$.
+The probability of $\hat{x}_i$ being in class $c$ will be given by the softmax function:
+
+!bt
+\[
+P(y_{ic} = 1 \mid \hat{x}_i, \hat{\theta}) = \frac{\exp{((\hat{a}_i^{hidden})^T \hat{w}_c)}}
+{\sum_{c'=0}^{C-1} \exp{((\hat{a}_i^{hidden})^T \hat{w}_{c'})}} ,
+\]
+!et
+
+which reduces to the logistic function in the binary case.
+The likelihood of this $C$-class classifier
+is now given as:
+
+!bt
+\[
+P(\mathcal{D} \mid \hat{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .
+\]
+!et
+Again we take the negative log-likelihood to define our cost function:
+
+!bt
+\[
+\mathcal{C}(\hat{\theta}) = - \log{P(\mathcal{D} \mid \hat{\theta})}.
+\]
+!et
+See the logistic regression lectures for a full definition of the cost function.
+
+The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!
+
+!split
+===== Example: binary classification problem =====
+
+As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as
+!bt
+\[
+\mathcal{C}(\hat{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\hat{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\hat{\beta})}\right),
+\]
+!et
+where we had defined the logistic (sigmoid) function
+!bt
+\[
+p(y_i =1\vert x_i,\hat{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}},
+\]
+!et
+and
+!bt
+\[
+p(y_i =0\vert x_i,\hat{\beta})=1-p(y_i =1\vert x_i,\hat{\beta}).
+\]
+!et
+The parameters $\hat{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method.
+
+Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$.
+We have then
+!bt
+\[
+a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}},
+\]
+!et
+with
+!bt
+\[
+z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,
+\]
+!et
+where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.
+Our cost function at the final layer $l=L$ is now
+!bt
+\[
+\mathcal{C}(\hat{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right),
+\]
+!et
+where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get
+!bt
+\[
+\frac{\partial \mathcal{C}(\hat{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.
+\]
+!et
+In case we use another activation function than the logistic one, we need to evaluate other derivatives.
+
+
+!split
+===== The Softmax function =====
+In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need
+!bt
+\[
+\frac{\partial f(z_i^l)}{\partial w_{jk}^l} =
+\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}.
+\]
+!et
+For the Softmax function we have
+!bt
+\[
+f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}.
+\]
+!et
+Its derivative with respect to $z_j^l$ gives
+!bt
+\[
+\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right),
+\]
+!et
+which in case of the simply binary model reduces to having $i=j$.
+
+!split
+===== Developing a code for doing neural networks with back propagation =====
+
+
+One can identify a set of key steps when using neural networks to solve supervised learning problems:
+
+o Collect and pre-process data
+o Define model and architecture
+o Choose cost function and optimizer
+o Train the model
+o Evaluate model performance on test data
+o Adjust hyperparameters (if necessary, network architecture)
+
+!split
+===== Collect and pre-process data =====
+
+Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_
+package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/".
+The *MNIST* (Modified National Institute of Standards and Technology) database is a large database
+of handwritten digits that is commonly used for training various image processing systems.
+The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9.
+The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database.
+
+To feed data into a feed-forward neural network we need to represent
+the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each
+row represents an *input*, in this case a handwritten digit, and
+each column represents a *feature*, in this case a pixel. The
+correct answers, also known as *labels* or *targets* are
+represented as a 1D array of integers
+$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.
+
+As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from
+measurements of height (in m)
+and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example:
+
+$$ X = \begin{bmatrix}
+1.85 & 81\\
+1.71 & 65\\
+1.95 & 103\\
+1.55 & 42\\
+1.63 & 56
+\end{bmatrix} ,$$
+
+and the targets would be:
+
+$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$
+
+Since each input image is a 2D matrix, we need to flatten the image
+(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a
+design/feature matrix. This means we lose all spatial information in the
+image, such as locality and translational invariance. More complicated
+architectures such as Convolutional Neural Networks can take advantage
+of such information, and are most commonly applied when analyzing
+images.
+
+
+!bc pycod
+# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+!ec
+
+!split
+===== Train and test datasets =====
+
+Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.
+
+We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing.
+
+It is important that the train and test datasets are drawn randomly from our dataset, to ensure
+no bias in the sampling.
+Say you are taking measurements of weather data to predict the weather in the coming 5 days.
+You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data
+collected from 12.00 to 24.00.
+
+
+!bc pycod
+from sklearn.model_selection import train_test_split
+
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+
+# equivalently in numpy
+def train_test_split_numpy(inputs, labels, train_size, test_size):
+ n_inputs = len(inputs)
+ inputs_shuffled = inputs.copy()
+ labels_shuffled = labels.copy()
+
+ np.random.shuffle(inputs_shuffled)
+ np.random.shuffle(labels_shuffled)
+
+ train_end = int(n_inputs*train_size)
+ X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
+ Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
+
+ return X_train, X_test, Y_train, Y_test
+
+#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
+
+print("Number of training images: " + str(len(X_train)))
+print("Number of test images: " + str(len(X_test)))
+!ec
+
+!split
+===== Define model and architecture =====
+
+Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have
+
+$$ z = \sum_{i=1}^n w_i a_i ,$$
+
+$$ y = f(z) ,$$
+
+where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer
+and $w_i$ is the weight to input $i$.
+The activation of the neurons in the input layer is just the features (e.g. a pixel value).
+
+The simplest activation function for a neuron is the *Heaviside* function:
+
+$$ f(z) =
+\begin{cases}
+1, & z > 0\\
+0, & \text{otherwise}
+\end{cases}
+$$
+
+A feed-forward neural network with this activation is known as a *perceptron*.
+For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer.
+This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy),
+and we call these architectures *multiclass perceptrons*.
+
+However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and
+Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function.
+
+Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU).
+We will be using the sigmoid function $\sigma(x)$:
+
+$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$
+
+which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.
+
+!split
+===== Layers =====
+
+* Input
+Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.
+
+* Hidden layer
+We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer.
+Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer.
+
+* Output
+If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,
+which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1.
+
+For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.
+
+Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function:
+
+$$ P(\text{class $j$} \mid \text{input $\hat{a}$}) = \frac{\exp{(\hat{a}^T \hat{w}_j)}}
+{\sum_{c=0}^{9} \exp{(\hat{a}^T \hat{w}_c)}} ,$$
+
+i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\hat{a}$, with $\hat{w}_j$ the weights of neuron $j$ to the inputs.
+The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1.
+The exponent is just the weighted sum of inputs as before:
+
+$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$
+
+Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500
+weights to the output layer.
+
+!split
+===== Weights and biases =====
+
+Typically weights are initialized with small values distributed around zero, drawn from a uniform
+or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless.
+
+Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range
+of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$:
+
+$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$
+
+The bias weights $\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle.
+!bc pycod
+# building our neural network
+
+n_inputs, n_features = X_train.shape
+n_hidden_neurons = 50
+n_categories = 10
+
+# we make the weights normally distributed using numpy.random.randn
+
+# weights and bias in the hidden layer
+hidden_weights = np.random.randn(n_features, n_hidden_neurons)
+hidden_bias = np.zeros(n_hidden_neurons) + 0.01
+
+# weights and bias in the output layer
+output_weights = np.random.randn(n_hidden_neurons, n_categories)
+output_bias = np.zeros(n_categories) + 0.01
+!ec
+
+!split
+===== Feed-forward pass =====
+
+Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories.
+For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$:
+
+$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$
+
+this is then passed through our activation function
+
+$$ a_{j}^{l} = f(z_{j}^{l}) .$$
+
+We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer:
+
+$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$
+
+Finally we calculate the output of neuron $j$ in the output layer using the softmax function:
+
+$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
+{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$
+
+!split
+===== Matrix multiplications =====
+
+Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden
+layer have the dimensions
+$W_{hidden} = (n_{features}, n_{hidden})$,
+we can easily feed the network all our training data in one go by taking the matrix product
+
+$$ X W^{h} = (n_{inputs}, n_{hidden}),$$
+
+and obtain a matrix that holds the weighted sum of inputs to the hidden layer
+for each input image and each hidden neuron.
+We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$:
+
+$$ \hat{z}^{l} = \hat{X} \hat{W}^{l} + \hat{b}^{l} ,$$
+
+meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image.
+This is then passed through the activation:
+
+$$ \hat{a}^{l} = f(\hat{z}^l) .$$
+
+This is fed to the output layer:
+
+$$ \hat{z}^{L} = \hat{a}^{L} \hat{W}^{L} + \hat{b}^{L} .$$
+
+Finally we receive our output values for each image and each category by passing it through the softmax function:
+
+$$ output = softmax (\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$
+
+
+!bc pycod
+# setup the feed-forward pass, subscript h = hidden layer
+
+def sigmoid(x):
+ return 1/(1 + np.exp(-x))
+
+def feed_forward(X):
+ # weighted sum of inputs to the hidden layer
+ z_h = np.matmul(X, hidden_weights) + hidden_bias
+ # activation in the hidden layer
+ a_h = sigmoid(z_h)
+
+ # weighted sum of inputs to the output layer
+ z_o = np.matmul(a_h, output_weights) + output_bias
+ # softmax output
+ # axis 0 holds each input and axis 1 the probabilities of each category
+ exp_term = np.exp(z_o)
+ probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
+
+ return probabilities
+
+probabilities = feed_forward(X_train)
+print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
+print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
+print("probabilities sum up to: " + str(probabilities[0].sum()))
+print()
+
+# we obtain a prediction by taking the class with the highest likelihood
+def predict(X):
+ probabilities = feed_forward(X)
+ return np.argmax(probabilities, axis=1)
+
+predictions = predict(X_train)
+print("predictions = (n_inputs) = " + str(predictions.shape))
+print("prediction for image 0: " + str(predictions[0]))
+print("correct label for image 0: " + str(Y_train[0]))
+!ec
+
+!split
+===== Choose cost function and optimizer =====
+
+To measure how well our neural network is doing we need to introduce a cost function.
+We will call the function that gives the error of a single sample output the *loss* function, and the function
+that gives the total error of our network across all samples the *cost* function.
+A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood.
+
+In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector:
+
+$$ y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$
+
+
+$$ y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$
+
+
+i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset.
+
+Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector.
+We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\hat{x}_i$ in the dataset.
+
+In the one-hot representation only one of the terms in the loss function is non-zero, namely the
+probability of the correct category $c'$
+(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong
+you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\hat{\theta}$ represents the parameters of our network, i.e. all the weights and biases.
+
+
+!split
+===== Optimizing the cost function =====
+
+The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent
+is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function.
+Each parameter $\theta$ is iteratively adjusted according to the rule
+
+$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$
+
+where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum.
+This update can be repeated for any number of iterations, or until we are satisfied with the result.
+
+A simple and effective improvement is a variant called *Batch Gradient Descent*.
+Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient
+on a subset of the data called a *minibatch*.
+If there are $N$ data points and we have a minibatch size of $M$, the total number of batches
+is $N/M$.
+We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes:
+
+$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad
+\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$
+
+i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.
+
+This has two important benefits:
+o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
+o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
+
+The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html".
+
+!split
+===== Regularization =====
+
+It is common to add an extra term to the cost function, proportional
+to the size of the weights. This is equivalent to constraining the
+size of the weights, so that they do not grow out of control.
+Constraining the size of the weights means that the weights cannot
+grow arbitrarily large to fit the training data, and in this way
+reduces *overfitting*.
+
+We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes:
+
+$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad
+\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2
+= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$
+
+i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter.
+
+
+In order to train the model, we need to calculate the derivative of
+the cost function with respect to every bias and weight in the
+network. In total our network has $(64 + 1)\times 50=3250$ weights in
+the hidden layer and $(50 + 1)\times 10=510$ weights to the output
+layer ($+1$ for the bias), and the gradient must be calculated for
+every parameter. We use the *backpropagation* algorithm discussed
+above. This is a clever use of the chain rule that allows us to
+calculate the gradient efficently.
+
+
+!split
+===== Matrix multiplication =====
+
+To more efficently train our network these equations are implemented using matrix operations.
+The error in the output layer is calculated simply as, with $\hat{t}$ being our targets,
+
+$$ \delta_L = \hat{t} - \hat{y} = (n_{inputs}, n_{categories}) .$$
+
+The gradient for the output weights is calculated as
+
+$$ \nabla W_{L} = \hat{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$
+
+where $\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input.
+Since we are going backwards we have to transpose the activation matrix.
+
+The gradient with respect to the output bias is then
+
+$$ \nabla \hat{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$
+
+The error in the hidden layer is
+
+$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$
+
+where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean
+that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes
+the *Hadamard product*, meaning element-wise multiplication.
+
+This again gives us the gradients in the hidden layer:
+
+$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$
+
+$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$
+
+
+!bc pycod
+# to categorical turns our integer vector into a onehot representation
+from sklearn.metrics import accuracy_score
+
+# one-hot in numpy
+def to_categorical_numpy(integer_vector):
+ n_inputs = len(integer_vector)
+ n_categories = np.max(integer_vector) + 1
+ onehot_vector = np.zeros((n_inputs, n_categories))
+ onehot_vector[range(n_inputs), integer_vector] = 1
+
+ return onehot_vector
+
+#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
+Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
+
+def feed_forward_train(X):
+ # weighted sum of inputs to the hidden layer
+ z_h = np.matmul(X, hidden_weights) + hidden_bias
+ # activation in the hidden layer
+ a_h = sigmoid(z_h)
+
+ # weighted sum of inputs to the output layer
+ z_o = np.matmul(a_h, output_weights) + output_bias
+ # softmax output
+ # axis 0 holds each input and axis 1 the probabilities of each category
+ exp_term = np.exp(z_o)
+ probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
+
+ # for backpropagation need activations in hidden and output layers
+ return a_h, probabilities
+
+def backpropagation(X, Y):
+ a_h, probabilities = feed_forward_train(X)
+
+ # error in the output layer
+ error_output = probabilities - Y
+ # error in the hidden layer
+ error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
+
+ # gradients for the output layer
+ output_weights_gradient = np.matmul(a_h.T, error_output)
+ output_bias_gradient = np.sum(error_output, axis=0)
+
+ # gradient for the hidden layer
+ hidden_weights_gradient = np.matmul(X.T, error_hidden)
+ hidden_bias_gradient = np.sum(error_hidden, axis=0)
+
+ return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
+
+print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
+
+eta = 0.01
+lmbd = 0.01
+for i in range(1000):
+ # calculate gradients
+ dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
+
+ # regularization term gradients
+ dWo += lmbd * output_weights
+ dWh += lmbd * hidden_weights
+
+ # update weights and biases
+ output_weights -= eta * dWo
+ output_bias -= eta * dBo
+ hidden_weights -= eta * dWh
+ hidden_bias -= eta * dBh
+
+print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
+!ec
+
+!split
+===== Improving performance =====
+
+As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image.
+In order to obtain a network that does something useful, we will have to do a bit more work.
+
+The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$.
+
+Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period
+going through the entire dataset ($n/M$ batches) an *epoch*.
+
+If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers.
+Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/".
+
+!split
+===== Full object-oriented implementation =====
+
+It is very natural to think of the network as an object, with specific instances of the network
+being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below.
+
+
+!bc pycod
+class NeuralNetwork:
+ def __init__(
+ self,
+ X_data,
+ Y_data,
+ n_hidden_neurons=50,
+ n_categories=10,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0):
+
+ self.X_data_full = X_data
+ self.Y_data_full = Y_data
+
+ self.n_inputs = X_data.shape[0]
+ self.n_features = X_data.shape[1]
+ self.n_hidden_neurons = n_hidden_neurons
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ self.create_biases_and_weights()
+
+ def create_biases_and_weights(self):
+ self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
+ self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
+
+ self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
+ self.output_bias = np.zeros(self.n_categories) + 0.01
+
+ def feed_forward(self):
+ # feed-forward for training
+ self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
+ self.a_h = sigmoid(self.z_h)
+
+ self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
+
+ exp_term = np.exp(self.z_o)
+ self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
+
+ def feed_forward_out(self, X):
+ # feed-forward for output
+ z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
+ a_h = sigmoid(z_h)
+
+ z_o = np.matmul(a_h, self.output_weights) + self.output_bias
+
+ exp_term = np.exp(z_o)
+ probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
+ return probabilities
+
+ def backpropagation(self):
+ error_output = self.probabilities - self.Y_data
+ error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
+
+ self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
+ self.output_bias_gradient = np.sum(error_output, axis=0)
+
+ self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
+ self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
+
+ if self.lmbd > 0.0:
+ self.output_weights_gradient += self.lmbd * self.output_weights
+ self.hidden_weights_gradient += self.lmbd * self.hidden_weights
+
+ self.output_weights -= self.eta * self.output_weights_gradient
+ self.output_bias -= self.eta * self.output_bias_gradient
+ self.hidden_weights -= self.eta * self.hidden_weights_gradient
+ self.hidden_bias -= self.eta * self.hidden_bias_gradient
+
+ def predict(self, X):
+ probabilities = self.feed_forward_out(X)
+ return np.argmax(probabilities, axis=1)
+
+ def predict_probabilities(self, X):
+ probabilities = self.feed_forward_out(X)
+ return probabilities
+
+ def train(self):
+ data_indices = np.arange(self.n_inputs)
+
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ # pick datapoints with replacement
+ chosen_datapoints = np.random.choice(
+ data_indices, size=self.batch_size, replace=False
+ )
+
+ # minibatch training data
+ self.X_data = self.X_data_full[chosen_datapoints]
+ self.Y_data = self.Y_data_full[chosen_datapoints]
+
+ self.feed_forward()
+ self.backpropagation()
+!ec
+
+!split
+===== Evaluate model performance on test data =====
+
+To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data.
+We measure the performance of the network using the *accuracy* score.
+The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$.
+
+$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\hat{y}_i = y_i)}{n} ,$$
+
+where $I$ is the indicator function, $1$ if $\hat{y}_i = y_i$ and $0$ otherwise.
+
+
+!bc pycod
+epochs = 100
+batch_size = 100
+
+dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
+ n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
+dnn.train()
+test_predict = dnn.predict(X_test)
+
+# accuracy score from scikit library
+print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
+
+# equivalent in numpy
+def accuracy_score_numpy(Y_test, Y_pred):
+ return np.sum(Y_test == Y_pred) / len(Y_test)
+
+#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
+!ec
+
+!split
+===== Adjust hyperparameters =====
+
+We now perform a grid search to find the optimal hyperparameters for the network.
+Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate).
+
+!bc pycod
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+# store the models for later use
+DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+# grid search
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
+ n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
+ dnn.train()
+
+ DNN_numpy[i][j] = dnn
+
+ test_predict = dnn.predict(X_test)
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
+ print()
+!ec
+
+!split
+===== Visualization =====
+
+!bc pycod
+# visual representation of grid search
+# uses seaborn heatmap, you can also do this with matplotlib imshow
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ dnn = DNN_numpy[i][j]
+
+ train_pred = dnn.predict(X_train)
+ test_pred = dnn.predict(X_test)
+
+ train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
+ test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!split
+===== scikit-learn implementation =====
+
+_scikit-learn_ focuses more
+on traditional machine learning methods, such as regression,
+clustering, decision trees, etc. As such, it has only two types of
+neural networks: Multi Layer Perceptron outputting continuous values,
+*MPLRegressor*, and Multi Layer Perceptron outputting labels,
+*MLPClassifier*. We will see how simple it is to use these classes.
+
+_scikit-learn_ implements a few improvements from our neural network,
+such as early stopping, a varying learning rate, different
+optimization methods, etc. We would therefore expect a better
+performance overall.
+
+!bc pycod
+from sklearn.neural_network import MLPClassifier
+# store models for later use
+DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
+ alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
+ dnn.fit(X_train, Y_train)
+
+ DNN_scikit[i][j] = dnn
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
+ print()
+!ec
+
+
+!split
+===== Visualization =====
+!bc pycod
+# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ dnn = DNN_scikit[i][j]
+
+ train_pred = dnn.predict(X_train)
+ test_pred = dnn.predict(X_test)
+
+ train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
+ test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+
+!split
+===== Building neural networks in Tensorflow and Keras =====
+
+Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn
+and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy
+and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer.
+
+In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite
+clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or
+NumPy arrays.
+
+!split
+===== Tensorflow =====
+
+Tensorflow is an open source library machine learning library
+developed by the Google Brain team for internal use. It was released
+under the Apache 2.0 open source license in November 9, 2015.
+
+Tensorflow is a computational framework that allows you to construct
+machine learning models at different levels of abstraction, from
+high-level, object-oriented APIs like Keras, down to the C++ kernels
+that Tensorflow is built upon. The higher levels of abstraction are
+simpler to use, but less flexible, and our choice of implementation
+should reflect the problems we are trying to solve.
+
+"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation
+in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*
+to represent your model, and then create a Tensorflow *session* to run the graph.
+
+In this guide we will analyze the same data as we did in our NumPy and
+scikit-learn tutorial, gathered from the MNIST database of images. We
+will give an introduction to the lower level Python Application
+Program Interfaces (APIs), and see how we use them to build our graph.
+Then we will build (effectively) the same graph in Keras, to see just
+how simple solving a machine learning problem can be.
+
+To install tensorflow on Unix/Linux systems, use pip as
+!bc pycod
+pip3 install tensorflow
+!ec
+and/or if you use _anaconda_, just write (or install from the graphical user interface)
+!bc pycod
+conda install tensorflow
+!ec
+
+!split
+===== Collect and pre-process data =====
+
+!bc pycod
+# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+!ec
+
+!bc pycod
+from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# one-hot representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+!ec
+
+!split
+===== Using TensorFlow backend =====
+
+o Define model and architecture
+o Choose cost function and optimizer
+
+!bc pycod
+import tensorflow as tf
+
+class NeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_neurons_layer1=100,
+ n_neurons_layer2=50,
+ n_categories=2,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0):
+
+ # keep track of number of steps
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs = X_train.shape[0]
+ self.n_features = X_train.shape[1]
+ self.n_neurons_layer1 = n_neurons_layer1
+ self.n_neurons_layer2 = n_neurons_layer2
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ # build network piece by piece
+ # name scopes (with) are used to enforce creation of new variables
+ # https://www.tensorflow.org/guide/variables
+ self.create_placeholders()
+ self.create_DNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ # placeholders are fine here, but "Datasets" are the preferred method
+ # of streaming data into a model
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_DNN(self):
+ with tf.name_scope('DNN'):
+ # the weights are stored to calculate regularization loss later
+
+ # Fully connected layer 1
+ self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)
+
+ # Fully connected layer 2
+ self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc2, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)
+ regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, axis=1)
+ labels = tf.argmax(self.Y, axis=1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([DNN.loss, DNN.optimizer],
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ accuracy = sess.run(DNN.accuracy,
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ step = sess.run(DNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_train,
+ DNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_test,
+ DNN.Y: self.Y_test})
+!ec
+
+
+!split
+===== Optimizing and using gradient descent =====
+
+!bc pycod
+epochs = 100
+batch_size = 100
+n_neurons_layer1 = 100
+n_neurons_layer2 = 50
+n_categories = 10
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+!ec
+
+
+!bc pycod
+DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_neurons_layer1, n_neurons_layer2, n_categories,
+ epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)
+ DNN.fit()
+
+ DNN_tf[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % DNN.test_accuracy)
+ print()
+!ec
+
+!bc pycod
+# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_tf[i][j]
+
+ train_accuracy[i][j] = DNN.train_accuracy
+ test_accuracy[i][j] = DNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!bc pycod
+# optional
+# we can use log files to visualize our graph in Tensorboard
+writer = tf.summary.FileWriter('logs/')
+writer.add_graph(tf.get_default_graph())
+!ec
+
+
+!split
+===== Using Keras =====
+
+Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface"
+that supports Tensorflow, CTNK and Theano as backends.
+If you have Tensorflow installed Keras is available through the *tf.keras* module.
+If you have Anaconda installed you may run the following command
+!bc pycod
+conda install keras
+!ec
+
+Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:
+
+!bc pycod
+pip3 install keras
+!ec
+or look up the "instructions here":"https://keras.io/".
+
+!bc pycod
+from keras.models import Sequential
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
+ model = Sequential()
+ model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax'))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
+!ec
+
+!bc pycod
+DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
+ eta=eta, lmbd=lmbd)
+ DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = DNN.evaluate(X_test, Y_test)
+
+ DNN_keras[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
+!ec
+
+!bc pycod
+# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_keras[i][j]
+
+ train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+
+
+
+!split
+===== Which activation function should I use? =====
+
+The Back propagation algorithm we derived above works by going from
+the output layer to the input layer, propagating the error gradient on
+the way. Once the algorithm has computed the gradient of the cost
+function with regards to each parameter in the network, it uses these
+gradients to update each parameter with a Gradient Descent (GD) step.
+
+
+Unfortunately for us, the gradients often get smaller and smaller as the
+algorithm progresses down to the first hidden layers. As a result, the
+GD update leaves the lower layer connection weights
+virtually unchanged, and training never converges to a good
+solution. This is known in the literature as
+_the vanishing gradients problem_.
+
+In other cases, the opposite can happen, namely the the gradients can grow bigger and
+bigger. The result is that many of the layers get large updates of the
+weights the
+algorithm diverges. This is the _exploding gradients problem_, which is
+mostly encountered in recurrent neural networks. More generally, deep
+neural networks suffer from unstable gradients, different layers may
+learn at widely different speeds
+
+!split
+===== Is the Logistic activation function (Sigmoid) our choice? =====
+
+Although this unfortunate behavior has been empirically observed for
+quite a while (it was one of the reasons why deep neural networks were
+mostly abandoned for a long time), it is only around 2010 that
+significant progress was made in understanding it.
+
+A paper titled "Understanding the Difficulty of Training Deep
+Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that
+the problems with the popular logistic
+sigmoid activation function and the weight initialization technique
+that was most popular at the time, namely random initialization using
+a normal distribution with a mean of 0 and a standard deviation of
+1.
+
+They showed that with this activation function and this
+initialization scheme, the variance of the outputs of each layer is
+much greater than the variance of its inputs. Going forward in the
+network, the variance keeps increasing after each layer until the
+activation function saturates at the top layers. This is actually made
+worse by the fact that the logistic function has a mean of 0.5, not 0
+(the hyperbolic tangent function has a mean of 0 and behaves slightly
+better than the logistic function in deep networks).
+
+
+!split
+===== The derivative of the Logistic funtion =====
+
+Looking at the logistic activation function, when inputs become large
+(negative or positive), the function saturates at 0 or 1, with a
+derivative extremely close to 0. Thus when backpropagation kicks in,
+it has virtually no gradient to propagate back through the network,
+and what little gradient exists keeps getting diluted as
+backpropagation progresses down through the top layers, so there is
+really nothing left for the lower layers.
+
+In their paper, Glorot and Bengio propose a way to significantly
+alleviate this problem. We need the signal to flow properly in both
+directions: in the forward direction when making predictions, and in
+the reverse direction when backpropagating gradients. We don’t want
+the signal to die out, nor do we want it to explode and saturate. For
+the signal to flow properly, the authors argue that we need the
+variance of the outputs of each layer to be equal to the variance of
+its inputs, and we also need the gradients to have equal variance
+before and after flowing through a layer in the reverse direction.
+
+
+
+One of the insights in the 2010 paper by Glorot and Bengio was that
+the vanishing/exploding gradients problems were in part due to a poor
+choice of activation function. Until then most people had assumed that
+if Nature had chosen to use roughly sigmoid activation functions in
+biological neurons, they must be an excellent choice. But it turns out
+that other activation functions behave much better in deep neural
+networks, in particular the ReLU activation function, mostly because
+it does not saturate for positive values (and also because it is quite
+fast to compute).
+
+
+!split
+===== The RELU function family =====
+
+The ReLU activation function suffers from a problem known as the dying
+ReLUs: during training, some neurons effectively die, meaning they
+stop outputting anything other than 0.
+
+In some cases, you may find that half of your network’s neurons are
+dead, especially if you used a large learning rate. During training,
+if a neuron’s weights get updated such that the weighted sum of the
+neuron’s inputs is negative, it will start outputting 0. When this
+happen, the neuron is unlikely to come back to life since the gradient
+of the ReLU function is 0 when its input is negative.
+
+To solve this problem, nowadays practitioners use a variant of the ReLU
+function, such as the leaky ReLU discussed above or the so-called
+exponential linear unit (ELU) function
+
+
+!bt
+\[
+ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
+\]
+!et
+
+!split
+===== Which activation function should we use? =====
+
+In general it seems that the ELU activation function is better than
+the leaky ReLU function (and its variants), which is better than
+ReLU. ReLU performs better than $\tanh$ which in turn performs better
+than the logistic function.
+
+If runtime
+performance is an issue, then you may opt for the leaky ReLU function over the
+ELU function If you don’t
+want to tweak yet another hyperparameter, you may just use the default
+$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have
+spare time and computing power, you can use cross-validation or
+bootstrap to evaluate other activation functions.
+
+
+!split
+===== A top-down perspective on Neural networks =====
+
+
+The first thing we would like to do is divide the data into two or three
+parts. A training set, a validation or dev (development) set, and a
+test set. The test set is the data on which we want to make
+predictions. The dev set is a subset of the training data we use to
+check how well we are doing out-of-sample, after training the model on
+the training dataset. We use the validation error as a proxy for the
+test error in order to make tweaks to our model. It is crucial that we
+do not use any of the test data to train the algorithm. This is a
+cardinal sin in ML. Then:
+
+
+* Estimate optimal error rate
+
+* Minimize underfitting (bias) on training data set.
+
+* Make sure you are not overfitting.
+
+If the validation and test sets are drawn from the same distributions,
+then a good performance on the validation set should lead to similarly
+good performance on the test set.
+
+However, sometimes
+the training data and test data differ in subtle ways because, for
+example, they are collected using slightly different methods, or
+because it is cheaper to collect data in one way versus another. In
+this case, there can be a mismatch between the training and test
+data. This can lead to the neural network overfitting these small
+differences between the test and training sets, and a poor performance
+on the test set despite having a good performance on the validation
+set. To rectify this, Andrew Ng suggests making two validation or dev
+sets, one constructed from the training data and one constructed from
+the test data. The difference between the performance of the algorithm
+on these two validation sets quantifies the train-test mismatch. This
+can serve as another important diagnostic when using DNNs for
+supervised learning.
+
+!split
+===== Limitations of supervised learning with deep networks =====
+
+Like all statistical methods, supervised learning using neural
+networks has important limitations. This is especially important when
+one seeks to apply these methods, especially to physics problems. Like
+all tools, DNNs are not a universal solution. Often, the same or
+better performance on a task can be achieved by using a few
+hand-engineered features (or even a collection of random
+features).
+
+Here we list some of the important limitations of supervised neural network based models.
+
+
+
+* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
+* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
+* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
+* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.
+
+Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.
+
+
diff --git a/doc/src/week41/figslides/cnn.jpeg b/doc/src/week41/figslides/cnn.jpeg
new file mode 100644
index 000000000..67bf3ced7
Binary files /dev/null and b/doc/src/week41/figslides/cnn.jpeg differ
diff --git a/doc/src/week41/figslides/nn.jpeg b/doc/src/week41/figslides/nn.jpeg
new file mode 100644
index 000000000..0a495cfe4
Binary files /dev/null and b/doc/src/week41/figslides/nn.jpeg differ
diff --git a/doc/src/week41/week41.do.txt b/doc/src/week41/week41.do.txt
new file mode 100644
index 000000000..77547edf1
--- /dev/null
+++ b/doc/src/week41/week41.do.txt
@@ -0,0 +1,608 @@
+TITLE: Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks
+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
+
+
+!split
+===== Convolutional Neural Networks (recognizing images) =====
+
+
+Convolutional neural networks (CNNs) were developed during the last
+decade of the previous century, with a focus on character recognition
+tasks. Nowadays, CNNs are a central element in the spectacular success
+of dee learning methods. The success in for example image
+classifications have made them a central tool for most machine
+learning practitioners.
+
+CNNs are very similar to ordinary Neural Networks.
+They are made up of neurons that have learnable weights and
+biases. Each neuron receives some inputs, performs a dot product and
+optionally follows it with a non-linearity. The whole network still
+expresses a single differentiable score function: from the raw image
+pixels on one end to class scores at the other. And they still have a
+loss function (for example Softmax) on the last (fully-connected) layer
+and all the tips/tricks we developed for learning regular Neural
+Networks still apply (back propagation, gradient descent etc etc).
+
+What is the difference? _CNN architectures make the explicit assumption that
+the inputs are images, which allows us to encode certain properties
+into the architecture. These then make the forward function more
+efficient to implement and vastly reduce the amount of parameters in
+the network._
+
+Here we provide only a superficial overview, for the more interested, we recommend highly the course
+"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
+and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/".
+
+Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf".
+
+!split
+===== Regular NNs don’t scale well to full images =====
+
+As an example, consider
+an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
+single fully-connected neuron in a first hidden layer of a regular
+Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
+seems manageable, but clearly this fully-connected structure does not
+scale to larger images. For example, an image of more respectable
+size, say $200\times 200\times 3$, would lead to neurons that have
+$200\times 200\times 3 = 120,000$ weights.
+
+We could have
+several such neurons, and the parameters would add up quickly! Clearly,
+this full connectivity is wasteful and the huge number of parameters
+would quickly lead to possible overfitting.
+
+FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network.
+
+!split
+===== 3D volumes of neurons =====
+
+Convolutional Neural Networks take advantage of the fact that the
+input consists of images and they constrain the architecture in a more
+sensible way.
+
+In particular, unlike a regular Neural Network, the
+layers of a CNN have neurons arranged in 3 dimensions: width,
+height, depth. (Note that the word depth here refers to the third
+dimension of an activation volume, not to the depth of a full Neural
+Network, which can refer to the total number of layers in a network.)
+
+To understand it better, the above example of an image
+with an input volume of
+activations has dimensions $32\times 32\times 3$ (width, height,
+depth respectively).
+
+The neurons in a layer will
+only be connected to a small region of the layer before it, instead of
+all of the neurons in a fully-connected manner. Moreover, the final
+output layer could for this specific image have dimensions $1\times 1 \times 10$,
+because by the
+end of the CNN architecture we will reduce the full image into a
+single vector of class scores, arranged along the depth
+dimension.
+
+FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
+
+
+
+!split
+===== Layers used to build CNNs =====
+
+
+A simple CNN is a sequence of layers, and every layer of a CNN
+transforms one volume of activations to another through a
+differentiable function. We use three main types of layers to build
+CNN architectures: Convolutional Layer, Pooling Layer, and
+Fully-Connected Layer (exactly as seen in regular Neural Networks). We
+will stack these layers to form a full CNN architecture.
+
+A simple CNN for image classification could have the architecture:
+
+* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
+* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
+* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
+* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
+* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
+
+
+!split
+===== Transforming images =====
+
+CNNs transform the original image layer by layer from the original
+pixel values to the final class scores.
+
+Observe that some layers contain
+parameters and other don’t. In particular, the CNN layers perform
+transformations that are a function of not only the activations in the
+input volume, but also of the parameters (the weights and biases of
+the neurons). On the other hand, the RELU/POOL layers will implement a
+fixed function. The parameters in the CONV/FC layers will be trained
+with gradient descent so that the class scores that the CNN computes
+are consistent with the labels in the training set for each image.
+
+
+!split
+===== CNNs in brief =====
+
+In summary:
+
+* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
+* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
+* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
+* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
+* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
+
+For more material on convolutional networks, we strongly recommend
+the course
+"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
+and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html".
+
+
+!split
+===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras =====
+
+
+As discussed above, CNNs are neural networks built from the assumption that the inputs
+to the network are 2D images. This is important because the number of features or pixels in images
+grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
+
+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
+are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer.
+In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
+matrices, typically 1 for each color dimension (Red, Green, Blue).
+
+
+!split
+===== Setting it up =====
+
+It means that to represent the entire
+dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions:
+!bt
+\[
+(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
+\]
+!et
+
+!split
+===== The MNIST dataset again =====
+
+The MNIST dataset consists of grayscale images with a pixel size of
+$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
+neuron in the first hidden layer.
+
+If we were to analyze images of size $128\times 128$ we would require
+$128 \times 128 = 16384$ weights to each neuron. Even worse if we were
+dealing with color images, as most images are, we have an image matrix
+of size $128\times 128$ for each color dimension (Red, Green, Blue),
+meaning 3 times the number of weights $= 49152$ are required for every
+single neuron in the first hidden layer.
+
+
+!split
+===== Strong correlations =====
+Images typically have strong local correlations, meaning that a small
+part of the image varies little from its neighboring regions. If for
+example we have an image of a blue car, we can roughly assume that a
+small blue part of the image is surrounded by other blue regions.
+
+Therefore, instead of connecting every single pixel to a neuron in the
+first hidden layer, as we have previously done with deep neural
+networks, we can instead connect each neuron to a small part of the
+image (in all 3 RGB depth dimensions). The size of each small area is
+fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field".
+
+
+!split
+===== Layers of a CNN =====
+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
+The input image is typically a square matrix of depth 3.
+
+A _convolution_ is performed on the image which outputs
+a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_.
+
+
+Each filter slides along the input image, taking the dot product
+between each small part of the image and the filter, in all depth
+dimensions. This is then passed through a non-linear function,
+typically the _Rectified Linear (ReLu)_ function, which serves as the
+activation of the neurons in the first convolutional layer. This is
+further passed through a _pooling layer_, which reduces the size of the
+convolutional layer, e.g. by taking the maximum or average across some
+small regions, and this serves as input to the next convolutional
+layer.
+
+
+!split
+===== Systematic reduction =====
+
+By systematically reducing the size of the input volume, through
+convolution and pooling, the network should create representations of
+small parts of the input, and then from them assemble representations
+of larger areas. The final pooling layer is flattened to serve as
+input to a hidden layer, such that each neuron in the final pooling
+layer is connected to every single neuron in the hidden layer. This
+then serves as input to the output layer, e.g. a softmax output for
+classification.
+
+
+!split
+===== Prerequisites: Collect and pre-process data =====
+!bc pycod
+# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+!ec
+
+
+!split
+===== Importing Keras and Tensorflow =====
+!bc pycod
+from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+!ec
+
+!split
+===== Using TensorFlow backend =====
+
+We need to define model and architecture and choose cost function and optmizer.
+!bc pycid
+
+import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_filters=10,
+ n_neurons_connected=50,
+ n_categories=10,
+ receptive_field=3,
+ stride=1,
+ padding=1,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0):
+
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+
+ self.n_filters = n_filters
+ self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+ self.n_neurons_connected = n_neurons_connected
+ self.n_categories = n_categories
+
+ self.receptive_field = receptive_field
+ self.stride = stride
+ self.strides = [stride, stride, stride, stride]
+ self.padding = padding
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ self.create_placeholders()
+ self.create_CNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_CNN(self):
+ with tf.name_scope('CNN'):
+
+ # Convolutional layer
+ self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+ b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+ z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+ a_conv = tf.nn.relu(z_conv)
+
+ # 2x2 max pooling
+ a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+
+ # Fully connected layer
+ a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+ self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+ b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+ a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+ regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, 1)
+ labels = tf.argmax(self.Y, 1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([CNN.loss, CNN.optimizer],
+ feed_dict={CNN.X: batch_X,
+ CNN.Y: batch_Y})
+ accuracy = sess.run(CNN.accuracy,
+ feed_dict={CNN.X: batch_X,
+ CNN.Y: batch_Y})
+ step = sess.run(CNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+ feed_dict={CNN.X: self.X_train,
+ CNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+ feed_dict={CNN.X: self.X_test,
+ CNN.Y: self.Y_test})
+!ec
+
+!split
+===== Train the model =====
+
+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
+!bc pycod
+epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+ n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+ eta=eta, lmbd=lmbd)
+ CNN.fit()
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % CNN.test_accuracy)
+ print()
+
+ CNN_tf[i][j] = CNN
+!ec
+
+!split
+===== Visualizing the results =====
+
+!bc pycod
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ CNN = CNN_tf[i][j]
+
+ train_accuracy[i][j] = CNN.train_accuracy
+ test_accuracy[i][j] = CNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!split
+===== Running with Keras =====
+
+!bc pycod
+from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+ n_filters, n_neurons_connected, n_categories,
+ eta, lmbd):
+ model = Sequential()
+ model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+ activation='relu', kernel_regularizer=l2(lmbd)))
+ model.add(MaxPooling2D(pool_size=(2, 2)))
+ model.add(Flatten())
+ model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+!ec
+
+!split
+===== Final part =====
+
+!bc pycod
+CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+ n_filters, n_neurons_connected, n_categories,
+ eta, lmbd)
+ CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = CNN.evaluate(X_test, Y_test)
+
+ CNN_keras[i][j] = CNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
+!ec
+
+!split
+===== Final visualization =====
+
+!bc
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ CNN = CNN_keras[i][j]
+
+ train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!split
+===== Fun links =====
+
+o "Self-Driving cars using a convolutional neural network":"https://arxiv.org/abs/1604.07316"
+o "Abstract art using convolutional neural networks":"https://deepdreamgenerator.com/"
+
+
diff --git a/doc/src/week42/week42.do.txt b/doc/src/week42/week42.do.txt
new file mode 100644
index 000000000..1c8957c2f
--- /dev/null
+++ b/doc/src/week42/week42.do.txt
@@ -0,0 +1,616 @@
+TITLE: Convolutional Neural Networks
+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
+
+!split
+===== To do list =====
+
+* add material about the mathematics, with more explanations
+* update codes to tensorflow 2
+* add more elaborated examples
+* update keras codes and think of pytorch examples?
+* Example on pollen cases https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0229751
+* Example on nuclear physics experiments
+!split
+===== Convolutional Neural Networks (recognizing images) =====
+
+
+Convolutional neural networks (CNNs) were developed during the last
+decade of the previous century, with a focus on character recognition
+tasks. Nowadays, CNNs are a central element in the spectacular success
+of dee learning methods. The success in for example image
+classifications have made them a central tool for most machine
+learning practitioners.
+
+CNNs are very similar to ordinary Neural Networks.
+They are made up of neurons that have learnable weights and
+biases. Each neuron receives some inputs, performs a dot product and
+optionally follows it with a non-linearity. The whole network still
+expresses a single differentiable score function: from the raw image
+pixels on one end to class scores at the other. And they still have a
+loss function (for example Softmax) on the last (fully-connected) layer
+and all the tips/tricks we developed for learning regular Neural
+Networks still apply (back propagation, gradient descent etc etc).
+
+What is the difference? _CNN architectures make the explicit assumption that
+the inputs are images, which allows us to encode certain properties
+into the architecture. These then make the forward function more
+efficient to implement and vastly reduce the amount of parameters in
+the network._
+
+Here we provide only a superficial overview, for the more interested, we recommend highly the course
+"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
+and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/".
+
+Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf".
+
+!split
+===== Regular NNs don’t scale well to full images =====
+
+As an example, consider
+an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
+single fully-connected neuron in a first hidden layer of a regular
+Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
+seems manageable, but clearly this fully-connected structure does not
+scale to larger images. For example, an image of more respectable
+size, say $200\times 200\times 3$, would lead to neurons that have
+$200\times 200\times 3 = 120,000$ weights.
+
+We could have
+several such neurons, and the parameters would add up quickly! Clearly,
+this full connectivity is wasteful and the huge number of parameters
+would quickly lead to possible overfitting.
+
+FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network.
+
+!split
+===== 3D volumes of neurons =====
+
+Convolutional Neural Networks take advantage of the fact that the
+input consists of images and they constrain the architecture in a more
+sensible way.
+
+In particular, unlike a regular Neural Network, the
+layers of a CNN have neurons arranged in 3 dimensions: width,
+height, depth. (Note that the word depth here refers to the third
+dimension of an activation volume, not to the depth of a full Neural
+Network, which can refer to the total number of layers in a network.)
+
+To understand it better, the above example of an image
+with an input volume of
+activations has dimensions $32\times 32\times 3$ (width, height,
+depth respectively).
+
+The neurons in a layer will
+only be connected to a small region of the layer before it, instead of
+all of the neurons in a fully-connected manner. Moreover, the final
+output layer could for this specific image have dimensions $1\times 1 \times 10$,
+because by the
+end of the CNN architecture we will reduce the full image into a
+single vector of class scores, arranged along the depth
+dimension.
+
+FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
+
+
+
+!split
+===== Layers used to build CNNs =====
+
+
+A simple CNN is a sequence of layers, and every layer of a CNN
+transforms one volume of activations to another through a
+differentiable function. We use three main types of layers to build
+CNN architectures: Convolutional Layer, Pooling Layer, and
+Fully-Connected Layer (exactly as seen in regular Neural Networks). We
+will stack these layers to form a full CNN architecture.
+
+A simple CNN for image classification could have the architecture:
+
+* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
+* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
+* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
+* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
+* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
+
+
+!split
+===== Transforming images =====
+
+CNNs transform the original image layer by layer from the original
+pixel values to the final class scores.
+
+Observe that some layers contain
+parameters and other don’t. In particular, the CNN layers perform
+transformations that are a function of not only the activations in the
+input volume, but also of the parameters (the weights and biases of
+the neurons). On the other hand, the RELU/POOL layers will implement a
+fixed function. The parameters in the CONV/FC layers will be trained
+with gradient descent so that the class scores that the CNN computes
+are consistent with the labels in the training set for each image.
+
+
+!split
+===== CNNs in brief =====
+
+In summary:
+
+* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
+* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
+* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
+* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
+* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
+
+For more material on convolutional networks, we strongly recommend
+the course
+"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
+and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html".
+
+
+!split
+===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras =====
+
+
+As discussed above, CNNs are neural networks built from the assumption that the inputs
+to the network are 2D images. This is important because the number of features or pixels in images
+grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
+
+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
+are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer.
+In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
+matrices, typically 1 for each color dimension (Red, Green, Blue).
+
+
+!split
+===== Setting it up =====
+
+It means that to represent the entire
+dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions:
+!bt
+\[
+(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
+\]
+!et
+
+!split
+===== The MNIST dataset again =====
+
+The MNIST dataset consists of grayscale images with a pixel size of
+$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
+neuron in the first hidden layer.
+
+If we were to analyze images of size $128\times 128$ we would require
+$128 \times 128 = 16384$ weights to each neuron. Even worse if we were
+dealing with color images, as most images are, we have an image matrix
+of size $128\times 128$ for each color dimension (Red, Green, Blue),
+meaning 3 times the number of weights $= 49152$ are required for every
+single neuron in the first hidden layer.
+
+
+!split
+===== Strong correlations =====
+Images typically have strong local correlations, meaning that a small
+part of the image varies little from its neighboring regions. If for
+example we have an image of a blue car, we can roughly assume that a
+small blue part of the image is surrounded by other blue regions.
+
+Therefore, instead of connecting every single pixel to a neuron in the
+first hidden layer, as we have previously done with deep neural
+networks, we can instead connect each neuron to a small part of the
+image (in all 3 RGB depth dimensions). The size of each small area is
+fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field".
+
+
+!split
+===== Layers of a CNN =====
+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
+The input image is typically a square matrix of depth 3.
+
+A _convolution_ is performed on the image which outputs
+a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_.
+
+
+Each filter slides along the input image, taking the dot product
+between each small part of the image and the filter, in all depth
+dimensions. This is then passed through a non-linear function,
+typically the _Rectified Linear (ReLu)_ function, which serves as the
+activation of the neurons in the first convolutional layer. This is
+further passed through a _pooling layer_, which reduces the size of the
+convolutional layer, e.g. by taking the maximum or average across some
+small regions, and this serves as input to the next convolutional
+layer.
+
+
+!split
+===== Systematic reduction =====
+
+By systematically reducing the size of the input volume, through
+convolution and pooling, the network should create representations of
+small parts of the input, and then from them assemble representations
+of larger areas. The final pooling layer is flattened to serve as
+input to a hidden layer, such that each neuron in the final pooling
+layer is connected to every single neuron in the hidden layer. This
+then serves as input to the output layer, e.g. a softmax output for
+classification.
+
+
+!split
+===== Prerequisites: Collect and pre-process data =====
+!bc pycod
+# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+!ec
+
+
+!split
+===== Importing Keras and Tensorflow =====
+!bc pycod
+from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+!ec
+
+!split
+===== Using TensorFlow backend =====
+
+We need to define model and architecture and choose cost function and optmizer.
+!bc pycid
+
+import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_filters=10,
+ n_neurons_connected=50,
+ n_categories=10,
+ receptive_field=3,
+ stride=1,
+ padding=1,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0):
+
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+
+ self.n_filters = n_filters
+ self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+ self.n_neurons_connected = n_neurons_connected
+ self.n_categories = n_categories
+
+ self.receptive_field = receptive_field
+ self.stride = stride
+ self.strides = [stride, stride, stride, stride]
+ self.padding = padding
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ self.create_placeholders()
+ self.create_CNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_CNN(self):
+ with tf.name_scope('CNN'):
+
+ # Convolutional layer
+ self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+ b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+ z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+ a_conv = tf.nn.relu(z_conv)
+
+ # 2x2 max pooling
+ a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+
+ # Fully connected layer
+ a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+ self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+ b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+ a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+ regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, 1)
+ labels = tf.argmax(self.Y, 1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([CNN.loss, CNN.optimizer],
+ feed_dict={CNN.X: batch_X,
+ CNN.Y: batch_Y})
+ accuracy = sess.run(CNN.accuracy,
+ feed_dict={CNN.X: batch_X,
+ CNN.Y: batch_Y})
+ step = sess.run(CNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+ feed_dict={CNN.X: self.X_train,
+ CNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+ feed_dict={CNN.X: self.X_test,
+ CNN.Y: self.Y_test})
+!ec
+
+!split
+===== Train the model =====
+
+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
+!bc pycod
+epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+ n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+ eta=eta, lmbd=lmbd)
+ CNN.fit()
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % CNN.test_accuracy)
+ print()
+
+ CNN_tf[i][j] = CNN
+!ec
+
+!split
+===== Visualizing the results =====
+
+!bc pycod
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ CNN = CNN_tf[i][j]
+
+ train_accuracy[i][j] = CNN.train_accuracy
+ test_accuracy[i][j] = CNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!split
+===== Running with Keras =====
+
+!bc pycod
+from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+ n_filters, n_neurons_connected, n_categories,
+ eta, lmbd):
+ model = Sequential()
+ model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+ activation='relu', kernel_regularizer=l2(lmbd)))
+ model.add(MaxPooling2D(pool_size=(2, 2)))
+ model.add(Flatten())
+ model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+!ec
+
+!split
+===== Final part =====
+
+!bc pycod
+CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+ n_filters, n_neurons_connected, n_categories,
+ eta, lmbd)
+ CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = CNN.evaluate(X_test, Y_test)
+
+ CNN_keras[i][j] = CNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
+!ec
+
+!split
+===== Final visualization =====
+
+!bc
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ CNN = CNN_keras[i][j]
+
+ train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+!ec
+
+!split
+===== Fun links =====
+
+o "Self-Driving cars using a convolutional neural network":"https://arxiv.org/abs/1604.07316"
+o "Abstract art using convolutional neural networks":"https://deepdreamgenerator.com/"
+
+
diff --git a/doc/src/week43/week43.do.txt b/doc/src/week43/week43.do.txt
new file mode 100644
index 000000000..cb081cbb7
--- /dev/null
+++ b/doc/src/week43/week43.do.txt
@@ -0,0 +1,1010 @@
+TITLE: Week 43: Dimensionality Reduction
+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
+
+
+!split
+===== Why should we think of reducing the dimensionality =====
+
+In addition to the plot of the features, we study now also the covariance (and the correlation matrix).
+We use also _Pandas_ to compute the correlation matrix.
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+import pandas as pd
+# Making a data frame
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+ _, bins = np.histogram(cancer.data[:,i], bins =50)
+ ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+ ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+ ax[i].set_title(cancer.feature_names[i])
+ ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+import seaborn as sns
+correlation_matrix = cancerpd.corr().round(1)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+plt.show()
+
+#print eigvalues of correlation matrix
+EigValues, EigVectors = np.linalg.eig(correlation_matrix)
+print(EigValues)
+!ec
+
+In the above example we note two things. In the first plot we display
+the overlap of benign and malignant tumors as functions of the various
+features in the Wisconsing breast cancer data set. We see that for
+some of the features we can distinguish clearly the benign and
+malignant cases while for other features we cannot. This can point to
+us which features may be of greater interest when we wish to classify
+a benign or not benign tumour.
+
+In the second figure we have computed the so-called correlation
+matrix, which in our case with thirty features becomes a $30\times 30$
+matrix.
+
+We constructed this matrix using _pandas_ via the statements
+!bc pycod
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+!ec
+and then
+!bc pycod
+correlation_matrix = cancerpd.corr().round(1)
+!ec
+
+Diagonalizing this matrix we can in turn say something about which
+features are of relevance and which are not. But before we proceed we
+need to define covariance and correlation matrices. This leads us to
+the classical Principal Component Analysis (PCA) theorem with
+applications.
+
+
+
+!split
+===== Basic ideas of the Principal Component Analysis (PCA) =====
+
+The principal component analysis deals with the problem of fitting a
+low-dimensional affine subspace $S$ of dimension $d$ much smaller than
+the totaldimension $D$ of the problem at hand (our data
+set). Mathematically it can be formulated as a statistical problem or
+a geometric problem. In our discussion of the theorem for the
+classical PCA, we will stay with a statistical approach. This is also
+what set the scene historically which for the PCA.
+
+We have a data set defined by a design/feature matrix $\bm{X}$ (see below for its definition)
+* Each data point is determined by $p$ extrinsic (measurement) variables
+* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?
+* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
+
+
+!split
+===== Introducing the Covariance and Correlation functions =====
+
+Before we discuss the PCA theorem, we need to remind ourselves about
+the definition of the covariance and the correlation function. These are quantities
+
+Suppose we have defined two vectors
+$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as
+!bt
+\[
+\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
+ \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\
+ \end{bmatrix},
+\]
+!et
+where for example
+!bt
+\[
+\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
+\]
+!et
+With this definition and recalling that the variance is defined as
+!bt
+\[
+\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
+\]
+!et
+we can rewrite the covariance matrix as
+!bt
+\[
+\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
+ \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\
+ \end{bmatrix}.
+\]
+!et
+
+The covariance takes values between zero and infinity and may thus
+lead to problems with loss of numerical precision for particularly
+large values. It is common to scale the covariance matrix by
+introducing instead the correlation matrix defined via the so-called
+correlation function
+
+!bt
+\[
+\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}.
+\]
+!et
+
+The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}]
+\in [-1,1]$. This avoids eventual problems with too large values. We
+can then define the correlation matrix for the two vectors $\bm{x}$
+and $\bm{y}$ as
+
+!bt
+\[
+\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\
+ \mathrm{corr}[\bm{y},\bm{x}] & 1 \\
+ \end{bmatrix},
+\]
+!et
+
+In the above example this is the function we constructed using _pandas_.
+
+!split
+===== Correlation Function and Design/Feature Matrix =====
+
+In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_
+we defined the design/feature matrix $\bm{X}$ as
+
+!bt
+\[
+\bm{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix},
+\]
+!et
+with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the
+entries $n$ being the row elements.
+We can rewrite the design/feature matrix in terms of its column vectors as
+!bt
+\[
+\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix},
+\]
+!et
+with a given vector
+!bt
+\[
+\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
+\]
+!et
+
+With these definitions, we can now rewrite our $2\times 2$
+correaltion/covariance matrix in terms of a moe general design/feature
+matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$
+covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$
+
+!bt
+\[
+\bm{C}[\bm{x}] = \begin{bmatrix}
+\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\
+\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\
+\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\
+\end{bmatrix},
+\]
+!et
+and the correlation matrix
+!bt
+\[
+\bm{K}[\bm{x}] = \begin{bmatrix}
+1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\
+\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\
+\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\
+\end{bmatrix},
+\]
+!et
+
+
+!split
+===== Covariance Matrix Examples =====
+
+
+The Numpy function _np.cov_ calculates the covariance elements using
+the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have
+the exact mean values. The following simple function uses the
+_np.vstack_ function which takes each vector of dimension $1\times n$
+and produces a $2\times n$ matrix $\bm{W}$
+
+
+!bt
+\[
+\bm{W} = \begin{bmatrix} x_0 & y_0 \\
+ x_1 & y_1 \\
+ x_2 & y_2\\
+ \dots & \dots \\
+ x_{n-2} & y_{n-2}\\
+ x_{n-1} & y_{n-1} &
+ \end{bmatrix},
+\]
+!et
+
+which in turn is converted into into the $2\times 2$ covariance matrix
+$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate
+the mean value of each set of samples $\bm{x}$ etc using the Numpy
+function _np.mean(x)_. We can also extract the eigenvalues of the
+covariance matrix through the _np.linalg.eig()_ function.
+
+!bc pycod
+# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+!ec
+
+!split
+===== Correlation Matrix =====
+
+The previous example can be converted into the correlation matrix by
+simply scaling the matrix elements with the variances. We should also
+subtract the mean values for each column. This leads to the following
+code which sets up the correlations matrix for the previous example in
+a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors).
+
+!bc pycod
+import numpy as np
+n = 100
+# define two vectors
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+!ec
+
+We see that the matrix elements along the diagonal are one as they
+should be and that the matrix is symmetric. Furthermore, diagonalizing
+this matrix we easily see that it is a positive definite matrix.
+
+The above procedure with _numpy_ can be made more compact if we use _pandas_.
+
+!split
+===== Correlation Matrix with Pandas =====
+
+We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code
+!bc pycod
+import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
+!ec
+
+
+We expand this model to the Franke function discussed above.
+
+!split
+===== Correlation Matrix with Pandas and the Franke function =====
+
+!bc pycod
+# Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+ term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+ term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+ term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+ term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+ return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+ if len(x.shape) > 1:
+ x = np.ravel(x)
+ y = np.ravel(y)
+
+ N = len(x)
+ l = int((n+1)*(n+2)/2) # Number of elements in beta
+ X = np.ones((N,l))
+
+ for i in range(1,n+1):
+ q = int((i)*(i+1)/2)
+ for k in range(i+1):
+ X[:,q+k] = (x**(i-k))*(y**k)
+
+ return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
+!ec
+
+We note here that the covariance is zero for the first rows and
+columns since all matrix elements in the design matrix were set to one
+(we are fitting the function in terms of a polynomial of degree $n$).
+
+This means that the variance for these elements will be zero and will
+cause problems when we set up the correlation matrix. We can simply
+drop these elements and construct a correlation
+matrix without these elements.
+
+
+!split
+===== Rewriting the Covariance and/or Correlation Matrix =====
+
+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as
+!bt
+\[
+\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T].
+\]
+!et
+
+To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$
+!bt
+\[
+\bm{X}=\begin{bmatrix}
+x_{00} & x_{01}\\
+x_{10} & x_{11}\\
+\end{bmatrix}=\begin{bmatrix}
+\bm{x}_{0} & \bm{x}_{1}\\
+\end{bmatrix}.
+\]
+!et
+
+If we then compute the expectation value
+!bt
+\[
+\mathbb{E}[\bm{X}\bm{X}^T] = \frac{1}{n}\bm{X}\bm{X}^T=\begin{bmatrix}
+x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
+x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
+\end{bmatrix},
+\]
+!et
+which is just
+!bt
+\[
+\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\
+ \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\
+ \end{bmatrix},
+\]
+!et
+where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$.
+
+It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$.
+
+
+!split
+===== Towards the PCA theorem =====
+
+We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as
+!bt
+\[
+\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T].
+\]
+!et
+Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\bm{S}$.
+These matrices are defined as $\bm{S}\in {\mathbb{R}}^{p\times p}$ and obey the orthogonality requirements $\bm{S}\bm{S}^T=\bm{S}^T\bm{S}=\bm{I}$. The matrix can be written out in terms of the column vectors $\bm{s}_i$ as $\bm{S}=[\bm{s}_0,\bm{s}_1,\dots,\bm{s}_{p-1}]$ and $\bm{s}_i \in {\mathbb{R}}^{p}$.
+
+Assume also that there is a transformation $\bm{S}\bm{C}[\bm{x}]\bm{S}^T=\bm{C}[\bm{y}]$ such that the new matrix $\bm{C}[\bm{y}]$ is diagonal with elements $[\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}]$.
+
+That is we have
+!bt
+\[
+\bm{C}[\bm{y}] = \mathbb{E}[\bm{S}\bm{X}\bm{X}^T\bm{S}^T]=\bm{S}\bm{C}[\bm{x}]\bm{S}^T,
+\]
+!et
+since the matrix $\bm{S}$ is not a data dependent matrix. Multiplying with $\bm{S}^T$ from the left we have
+!bt
+\[
+\bm{S}^T\bm{C}[\bm{y}] = \bm{C}[\bm{x}]\bm{S}^T,
+\]
+!et
+and since $\bm{C}[\bm{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that
+
+!bt
+\[
+\bm{S}^T_i\lambda_i = \bm{C}[\bm{x}]\bm{S}^T_i.
+\]
+!et
+
+In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is
+$\lambda_0 > \lambda_1 > \dots > \lambda_{p-1}$.
+
+
+The eigenvalues tell us then how much we need to stretch the
+corresponding eigenvectors. Dimensions with large eigenvalues have
+thus large variations (large variance) and define therefore useful
+dimensions. The data points are more spread out in the direction of
+these eigenvectors. Smaller eigenvalues mean on the other hand that
+the corresponding eigenvectors are shrunk accordingly and the data
+points are tightly bunched together and there is not much variation in
+these specific directions. Hopefully then we could leave it out
+dimensions where the eigenvalues are very small. If $p$ is very large,
+we could then aim at reducing $p$ to $l << p$ and handle only $l$
+features/predictors.
+
+!split
+===== The Algorithm before the Theorem =====
+
+Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.
+* Set up the datapoints for the design/feature matrix $\bm{X}$ with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements.
+!bt
+\[
+\bm{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix},
+\]
+!et
+* Center the data by subtracting the mean value for each column. This leads to a new matrix $\bm{X}\rightarrow \overline{\bm{X}}$.
+* Compute then the covariance/correlation matrix $\mathbb{E}[\overline{\bm{X}}\overline{\bm{X}}^T]$.
+* Find the eigenpairs of $\bm{C}$ with eigenvalues $[\lambda_0,\lambda_1,\dots,\lambda_{p-1}]$ and eigenvectors $[\bm{s}_0,\bm{s}_1,\dots,\bm{s}_{p-1}]$.
+* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
+* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here.
+
+
+!split
+===== Writing our own PCA code =====
+
+We will use a simple example first with two-dimensional data
+drawn from a multivariate normal distribution with the following mean and covariance matrix:
+!bt
+\[
+\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\
+2 & 2
+\end{bmatrix}
+\]
+!et
+Note that the mean refers to each column of data.
+We will generate $n = 1000$ points $X = \{ x_1, \ldots, x_N \}$ from
+this distribution, and store them in the $1000 \times 2$ matrix $\bm{X}$.
+
+The following Python code aids in setting up the data and writing out the design matrix.
+Note that the function _multivariate_ returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$.
+!bc pycod
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+n = 10000
+mean = (-1, 2)
+cov = [[4, 2], [2, 2]]
+X = np.random.multivariate_normal(mean, cov, n)
+!ec
+
+Now we are going to implement the PCA algorithm. We will break it down into various substeps.
+
+=== Compute the sample mean and center the data ===
+
+The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is
+!bt
+\[
+\mu_n = \frac{1}{n} \sum_{i=1}^n x_i
+\]
+!et
+and the mean-centered data $\bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \}$ takes the form
+!bt
+\[
+\bar{x}_i = x_i - \mu_n.
+\]
+!et
+When you are done with these steps, print out $\mu_n$ to verify it is
+close to $\mu$ and plot your mean centered data to verify it is
+centered at the origin! Compare your code with the functionality from _Scikit-Learn_ discussed above.
+The following code elements perform these operations using _pandas_ or using our own functionality for doing so. The latter, using _numpy_ is rather simple through the _mean()_ function.
+!bc pycod
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+!ec
+
+Alternatively, we could use the functions we discussed
+earlier for scaling the data set. That is, we could have used the
+_StandardScaler_ function in _Scikit-Learn_, a function which ensures
+that for each feature/predictor we study the mean value is zero and
+the variance is one (every column in the design/feature matrix). You
+would then not get the same results, since we divide by the
+variance. The diagonal covariance matrix elements will then be one,
+while the non-diagonal ones need to be divided by $2\sqrt{2}$ for our
+specific case.
+
+=== Compute the sample covariance ===
+
+Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation
+!bt
+\begin{equation*}
+\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n)
+\end{equation*}
+!et
+where the data points $x_i \in \mathbb{R}^p$ (here in this example $p = 2$) are column vectors and $x^T$ is the transpose of $x$.
+We can write our own code or simply use either the functionaly of _numpy_ or that of _pandas_, as follows
+!bc pycod
+print(df.cov())
+print(np.cov(X_centered.T))
+!ec
+Note that the way we define the covariance matrix here has a factor $n-1$ instead of $n$. This is included in the _cov()_ function by _numpy_ and _pandas_.
+Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\times 2$ covariance matrix.
+!bc pycod
+# extract the relevant columns from the centered design matrix of dim n x 2
+x = X_centered[:,0]
+y = X_centered[:,1]
+Cov = np.zeros((2,2))
+Cov[0,1] = np.sum(x.T@y)/(n-1.0)
+Cov[0,0] = np.sum(x.T@x)/(n-1.0)
+Cov[1,1] = np.sum(y.T@y)/(n-1.0)
+Cov[1,0]= Cov[0,1]
+print("Centered covariance using own code")
+print(Cov)
+plt.plot(x, y, 'x')
+plt.axis('equal')
+plt.show()
+!ec
+
+Depending on the number of points $n$, we will get results that are close to the covariance values defined above.
+The plot shows how the data are clustered around a line with slope close to one. Is this expected?
+
+=== Diagonalize the sample covariance matrix to obtain the principal components ===
+
+Now we are ready to solve for the principal components! To do so we
+diagonalize the sample covariance matrix $\Sigma$. We can use the
+function _np.linalg.eig_ to do so. It will return the eigenvalues and
+eigenvectors of $\Sigma$. Once we have these we can perform the
+following tasks:
+
+* We compute the percentage of the total variance captured by the first principal component
+* We plot the mean centered data and lines along the first and second principal components
+* Then we project the mean centered data onto the first and second principal components, and plot the projected data.
+* Finally, we approximate the data as
+
+!bt
+\begin{equation*}
+x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0
+\end{equation*}
+!et
+where $v_0$ is the first principal component.
+
+Collecting all these steps we can write our own PCA function and
+compare this with the functionality included in _Scikit-Learn_.
+
+The code here outlines some of the elements we could include in the
+analysis. Feel free to extend upon this in order to address the above
+questions.
+
+!bc pycod
+# diagonalize and obtain eigenvalues, not necessarily sorted
+EigValues, EigVectors = np.linalg.eig(Cov)
+# sort eigenvectors and eigenvalues
+#permute = EigValues.argsort()
+#EigValues = EigValues[permute]
+#EigVectors = EigVectors[:,permute]
+print("Eigenvalues of Covariance matrix")
+for i in range(2):
+ print(EigValues[i])
+FirstEigvector = EigVectors[:,0]
+SecondEigvector = EigVectors[:,1]
+print("First eigenvector")
+print(FirstEigvector)
+print("Second eigenvector")
+print(SecondEigvector)
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2Dsl = pca.fit_transform(X)
+print("Eigenvector of largest eigenvalue")
+print(pca.components_.T[:, 0])
+
+!ec
+This code does not contain all the above elements, but it shows how we can use _Scikit-Learn_ to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then?
+
+!split
+===== Classical PCA Theorem =====
+
+We assume now that we have a design matrix $\bm{X}$ which has been
+centered as discussed above. For the sake of simplicity we skip the
+overline symbol. The matrix is defined in terms of the various column
+vectors $[\bm{x}_0,\bm{x}_1,\dots, \bm{x}_{p-1}]$ each with dimension
+$\bm{x}\in {\mathbb{R}}^{n}$.
+
+We assume also that we have an orthogonal transformation $\bm{W}\in {\mathbb{R}}^{p\times p}$. We define the reconstruction error (which is similar to the mean squared error we have seen before) as
+!bt
+\[
+J(\bm{W},\bm{Z}) = \frac{1}{n}\sum_i (\bm{x}_i - \overline{\bm{x}}_i)^2,
+\]
+!et
+with $\overline{\bm{x}}_i = \bm{W}\bm{z}_i$, where $\bm{z}_i$ is a row vector with dimension ${\mathbb{R}}^{n}$ of the matrix
+$\bm{Z}\in{\mathbb{R}}^{p\times n}$. When doing PCA we want to reduce this dimensionality.
+
+The PCA theorem states that minimizing the above reconstruction error
+corresponds to setting $\bm{W}=\bm{S}$, the orthogonal matrix which
+diagonalizes the empirical covariance(correlation) matrix. The optimal
+low-dimensional encoding of the data is then given by a set of vectors
+$\bm{z}_i$ with at most $l$ vectors, with $l << p$, defined by the
+orthogonal projection of the data onto the columns spanned by the
+eigenvectors of the covariance(correlations matrix).
+
+The proof which follows will be updated by mid January 2020.
+
+!split
+===== Proof of the PCA Theorem =====
+
+To show the PCA theorem let us start with the assumption that there is one vector $\bm{w}_0$ which corresponds to a solution which minimized the reconstruction error $J$. This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of $\bm{w}_0$ and $\bm{z}_0$ as
+!bt
+\[
+J(\bm{w}_0,\bm{z}_0)= \frac{1}{n}\sum_i (\bm{x}_i - z_{i0}\bm{w}_0)^2=\frac{1}{n}\sum_i (\bm{x}_i^T\bm{x}_i - 2z_{i0}\bm{w}_0^T\bm{x}_i+z_{i0}^2\bm{w}_0^T\bm{w}_0),
+\]
+!et
+which we can rewrite due to the orthogonality of $\bm{w}_i$ as
+!bt
+\[
+J(\bm{w}_0,\bm{z}_0)=\frac{1}{n}\sum_i (\bm{x}_i^T\bm{x}_i - 2z_{i0}\bm{w}_0^T\bm{x}_i+z_{i0}^2).
+\]
+!et
+Minimizing $J$ with respect to the unknown parameters $z_{0i}$ we obtain that
+!bt
+\[
+z_{i0}=\bm{w}_0^T\bm{x}_i,
+\]
+!et
+where the vectors on the rhs are known.
+
+
+!split
+===== PCA Proof continued =====
+
+We have now found the unknown parameters $z_{i0}$. These correspond to the projected coordinates and we can write
+!bt
+\[
+J(\bm{w}_0)= \frac{1}{p}\sum_i (\bm{x}_i^T\bm{x}_i - z_{i0}^2)=\mathrm{const}-\frac{1}{n}\sum_i z_{i0}^2.
+\]
+!et
+
+We can show that the variance of the projected coordinates defined by $\bm{w}_0^T\bm{x}_i$ are given by
+!bt
+\[
+\mathrm{var}[\bm{w}_0^T\bm{x}_i] = \frac{1}{n}\sum_i z_{i0}^2,
+\]
+!et
+since the expectation value of
+!bt
+\[
+\mathbb{E}[\bm{w}_0^T\bm{x}_i] = \mathbb{E}[z_{i0}]= \bm{w}_0^T\mathbb{E}[\bm{x}_i]=0,
+\]
+!et
+where we have used the fact that our data are centered.
+
+Recalling our definition of the covariance as
+!bt
+\[
+\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T=\mathbb{E}[\bm{X}\bm{X}^T],
+\]
+!et
+we have thus that
+!bt
+\[
+\mathrm{var}[\bm{w}_0^T\bm{x}_i] = \frac{1}{n}\sum_i z_{i0}^2=\bm{w}_0^T\bm{C}[\bm{x}]\bm{w}_0.
+\]
+!et
+
+We are almost there, we have obtained a relation between minimizing
+the reconstruction error and the variance and the covariance
+matrix. Minimizing the error is equivalent to maximizing the variance
+of the projected data.
+
+!split
+===== The final step =====
+
+We could trivially maximize the variance of the projection (and
+thereby minimize the error in the reconstruction function) by letting
+the norm-2 of $\bm{w}_0$ go to infinity. However, this norm since we
+want the matrix $\bm{W}$ to be an orthogonal matrix, is constrained by
+$\vert\vert \bm{w}_0 \vert\vert_2^2=1$. Imposing this condition via a
+Lagrange multiplier we can then in turn maximize
+
+!bt
+\[
+J(\bm{w}_0)= \bm{w}_0^T\bm{C}[\bm{x}]\bm{w}_0+\lambda_0(1-\bm{w}_0^T\bm{w}_0).
+\]
+!et
+Taking the derivative with respect to $\bm{w}_0$ we obtain
+
+!bt
+\[
+\frac{\partial J(\bm{w}_0)}{\partial \bm{w}_0}= 2\bm{C}[\bm{x}]\bm{w}_0-2\lambda_0\bm{w}_0=0,
+\]
+!et
+meaning that
+!bt
+\[
+\bm{C}[\bm{x}]\bm{w}_0=\lambda_0\bm{w}_0.
+\]
+!et
+_The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix_! If we left multiply with $\bm{w}_0^T$ we have the variance of the projected data is
+!bt
+\[
+\bm{w}_0^T\bm{C}[\bm{x}]\bm{w}_0=\lambda_0.
+\]
+!et
+
+If we want to maximize the variance (minimize the construction error)
+we simply pick the eigenvector of the covariance matrix with the
+largest eigenvalue. This establishes the link between the minimization
+of the reconstruction function $J$ in terms of an orthogonal matrix
+and the maximization of the variance and thereby the covariance of our
+observations encoded in the design/feature matrix $\bm{X}$.
+
+The proof
+for the other eigenvectors $\bm{w}_1,\bm{w}_2,\dots$ can be
+established by applying the above arguments and using the fact that
+our basis of eigenvectors is orthogonal, see "Murphy chapter
+12.2":"https://mitpress.mit.edu/books/machine-learning-1". The
+discussion in chapter 12.2 of Murphy's text has also a nice link with
+the Singular Value Decomposition theorem. For categorical data, see
+chapter 12.4 and discussion therein.
+
+Additional part of the proof for the other eigenvectors will be added by mid January 2020.
+
+!split
+===== Geometric Interpretation and link with Singular Value Decomposition =====
+
+This material will be added by mid January 2020.
+
+
+!split
+===== Principal Component Analysis =====
+
+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.
+First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.
+
+The following Python code uses NumPy’s _svd()_ function to obtain all the principal components of the
+training set, then extracts the first two principal components. First we center the data using either _pandas_ or our own code
+!bc pycod
+import numpy as np
+import pandas as pd
+from IPython.display import display
+np.random.seed(100)
+# setting up a 10 x 5 vanilla matrix
+rows = 10
+cols = 5
+X = np.random.randn(rows,cols)
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+display(df)
+
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+# Then check the difference between pandas and our own set up
+print(X_centered-df)
+#Now we do an SVD
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+print(X2D)
+!ec
+
+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering
+the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t
+forget to center the data first.
+
+Once you have identified all the principal components, you can reduce the dimensionality of the dataset
+down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.
+Selecting this hyperplane ensures that the projection will preserve as much variance as possible.
+!bc pycod
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+!ec
+
+!split
+===== PCA and scikit-learn =====
+
+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
+following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note
+that it automatically takes care of centering the data):
+!bc pycod
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+print(X2D)
+!ec
+After fitting the PCA transformer to the dataset, you can access the principal components using the
+components variable (note that it contains the PCs as horizontal vectors, so, for example, the first
+principal component is equal to
+!bc pycod
+pca.components_.T[:, 0].
+!ec
+Another very useful piece of information is the explained variance ratio of each principal component,
+available via the $explained\_variance\_ratio$ variable. It indicates the proportion of the dataset’s
+variance that lies along the axis of each principal component.
+
+!split
+===== Back to the Cancer Data =====
+We can now repeat the above but applied to real data, in this case our breast cancer data.
+Here we compute performance scores on the training data using logistic regression.
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
+# We scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Then perform again a log reg fit
+logreg.fit(X_train_scaled, y_train)
+print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D_train = pca.fit_transform(X_train_scaled)
+# and finally compute the log reg fit and the score on the training data
+logreg.fit(X2D_train,y_train)
+print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
+
+!ec
+
+We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.
+
+!split
+===== More on the PCA =====
+
+Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
+choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
+Unless, of course, you are reducing dimensionality for data visualization — in that case you will
+generally want to reduce the dimensionality down to 2 or 3.
+The following code computes PCA without reducing dimensionality, then computes the minimum number
+of dimensions required to preserve 95% of the training set’s variance:
+!bc pycod
+pca = PCA()
+pca.fit(X)
+cumsum = np.cumsum(pca.explained_variance_ratio_)
+d = np.argmax(cumsum >= 0.95) + 1
+!ec
+You could then set $n\_components=d$ and run PCA again. However, there is a much better option: instead
+of specifying the number of principal components you want to preserve, you can set $n\_components$ to be
+a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:
+!bc pycod
+pca = PCA(n_components=0.95)
+X_reduced = pca.fit_transform(X)
+!ec
+
+!split
+===== Incremental PCA =====
+
+One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
+memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
+been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
+at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new
+instances arrive).
+
+!split
+===== Randomized PCA =====
+
+Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
+algorithm that quickly finds an approximation of the first d principal components. Its computational
+complexity is $O(m \times d^2)+O(d^3)$, instead of $O(m \times n^2) + O(n^3)$, so it is dramatically faster than the
+previous algorithms when $d$ is much smaller than $n$.
+
+
+
+
+!split
+===== Kernel PCA =====
+!bblock
+
+The kernel trick is a mathematical technique that implicitly maps instances into a
+very high-dimensional space (called the feature space), enabling nonlinear classification and regression
+with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature
+space corresponds to a complex nonlinear decision boundary in the original space.
+It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear
+projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at
+preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a
+twisted manifold.
+For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an
+!bc pycod
+from sklearn.decomposition import KernelPCA
+rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
+X_reduced = rbf_pca.fit_transform(X)
+!ec
+
+!eblock
+
+
+!split
+===== LLE =====
+
+Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction
+(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous
+algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its
+closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where
+these local relationships are best preserved (more details shortly).
+
+
+
+!split
+===== Other techniques =====
+
+
+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
+
+Here are some of the most popular:
+* _Multidimensional Scaling (MDS)_ reduces dimensionality while trying to preserve the distances between the instances.
+* _Isomap_ creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.
+* _t-Distributed Stochastic Neighbor Embedding_ (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).
+* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.
+
+
diff --git a/doc/src/week44/DataFiles/bank.csv b/doc/src/week44/DataFiles/bank.csv
new file mode 100644
index 000000000..930337395
--- /dev/null
+++ b/doc/src/week44/DataFiles/bank.csv
@@ -0,0 +1,1372 @@
+3.6216,8.6661,-2.8073,-0.44699,0
+4.5459,8.1674,-2.4586,-1.4621,0
+3.866,-2.6383,1.9242,0.10645,0
+3.4566,9.5228,-4.0112,-3.5944,0
+0.32924,-4.4552,4.5718,-0.9888,0
+4.3684,9.6718,-3.9606,-3.1625,0
+3.5912,3.0129,0.72888,0.56421,0
+2.0922,-6.81,8.4636,-0.60216,0
+3.2032,5.7588,-0.75345,-0.61251,0
+1.5356,9.1772,-2.2718,-0.73535,0
+1.2247,8.7779,-2.2135,-0.80647,0
+3.9899,-2.7066,2.3946,0.86291,0
+1.8993,7.6625,0.15394,-3.1108,0
+-1.5768,10.843,2.5462,-2.9362,0
+3.404,8.7261,-2.9915,-0.57242,0
+4.6765,-3.3895,3.4896,1.4771,0
+2.6719,3.0646,0.37158,0.58619,0
+0.80355,2.8473,4.3439,0.6017,0
+1.4479,-4.8794,8.3428,-2.1086,0
+5.2423,11.0272,-4.353,-4.1013,0
+5.7867,7.8902,-2.6196,-0.48708,0
+0.3292,-4.4552,4.5718,-0.9888,0
+3.9362,10.1622,-3.8235,-4.0172,0
+0.93584,8.8855,-1.6831,-1.6599,0
+4.4338,9.887,-4.6795,-3.7483,0
+0.7057,-5.4981,8.3368,-2.8715,0
+1.1432,-3.7413,5.5777,-0.63578,0
+-0.38214,8.3909,2.1624,-3.7405,0
+6.5633,9.8187,-4.4113,-3.2258,0
+4.8906,-3.3584,3.4202,1.0905,0
+-0.24811,-0.17797,4.9068,0.15429,0
+1.4884,3.6274,3.308,0.48921,0
+4.2969,7.617,-2.3874,-0.96164,0
+-0.96511,9.4111,1.7305,-4.8629,0
+-1.6162,0.80908,8.1628,0.60817,0
+2.4391,6.4417,-0.80743,-0.69139,0
+2.6881,6.0195,-0.46641,-0.69268,0
+3.6289,0.81322,1.6277,0.77627,0
+4.5679,3.1929,-2.1055,0.29653,0
+3.4805,9.7008,-3.7541,-3.4379,0
+4.1711,8.722,-3.0224,-0.59699,0
+-0.2062,9.2207,-3.7044,-6.8103,0
+-0.0068919,9.2931,-0.41243,-1.9638,0
+0.96441,5.8395,2.3235,0.066365,0
+2.8561,6.9176,-0.79372,0.48403,0
+-0.7869,9.5663,-3.7867,-7.5034,0
+2.0843,6.6258,0.48382,-2.2134,0
+-0.7869,9.5663,-3.7867,-7.5034,0
+3.9102,6.065,-2.4534,-0.68234,0
+1.6349,3.286,2.8753,0.087054,0
+4.3239,-4.8835,3.4356,-0.5776,0
+5.262,3.9834,-1.5572,1.0103,0
+3.1452,5.825,-0.51439,-1.4944,0
+2.549,6.1499,-1.1605,-1.2371,0
+4.9264,5.496,-2.4774,-0.50648,0
+4.8265,0.80287,1.6371,1.1875,0
+2.5635,6.7769,-0.61979,0.38576,0
+5.807,5.0097,-2.2384,0.43878,0
+3.1377,-4.1096,4.5701,0.98963,0
+-0.78289,11.3603,-0.37644,-7.0495,0
+2.888,0.44696,4.5907,-0.24398,0
+0.49665,5.527,1.7785,-0.47156,0
+4.2586,11.2962,-4.0943,-4.3457,0
+1.7939,-1.1174,1.5454,-0.26079,0
+5.4021,3.1039,-1.1536,1.5651,0
+2.5367,2.599,2.0938,0.20085,0
+4.6054,-4.0765,2.7587,0.31981,0
+2.4235,9.5332,-3.0789,-2.7746,0
+1.0009,7.7846,-0.28219,-2.6608,0
+0.12326,8.9848,-0.9351,-2.4332,0
+3.9529,-2.3548,2.3792,0.48274,0
+4.1373,0.49248,1.093,1.8276,0
+4.7181,10.0153,-3.9486,-3.8582,0
+4.1654,-3.4495,3.643,1.0879,0
+4.4069,10.9072,-4.5775,-4.4271,0
+2.3066,3.5364,0.57551,0.41938,0
+3.7935,7.9853,-2.5477,-1.872,0
+0.049175,6.1437,1.7828,-0.72113,0
+0.24835,7.6439,0.9885,-0.87371,0
+1.1317,3.9647,3.3979,0.84351,0
+2.8033,9.0862,-3.3668,-1.0224,0
+4.4682,2.2907,0.95766,0.83058,0
+5.0185,8.5978,-2.9375,-1.281,0
+1.8664,7.7763,-0.23849,-2.9634,0
+3.245,6.63,-0.63435,0.86937,0
+4.0296,2.6756,0.80685,0.71679,0
+-1.1313,1.9037,7.5339,1.022,0
+0.87603,6.8141,0.84198,-0.17156,0
+4.1197,-2.7956,2.0707,0.67412,0
+3.8027,0.81529,2.1041,1.0245,0
+1.4806,7.6377,-2.7876,-1.0341,0
+4.0632,3.584,0.72545,0.39481,0
+4.3064,8.2068,-2.7824,-1.4336,0
+2.4486,-6.3175,7.9632,0.20602,0
+3.2718,1.7837,2.1161,0.61334,0
+-0.64472,-4.6062,8.347,-2.7099,0
+2.9543,1.076,0.64577,0.89394,0
+2.1616,-6.8804,8.1517,-0.081048,0
+3.82,10.9279,-4.0112,-5.0284,0
+-2.7419,11.4038,2.5394,-5.5793,0
+3.3669,-5.1856,3.6935,-1.1427,0
+4.5597,-2.4211,2.6413,1.6168,0
+5.1129,-0.49871,0.62863,1.1189,0
+3.3397,-4.6145,3.9823,-0.23751,0
+4.2027,0.22761,0.96108,0.97282,0
+3.5438,1.2395,1.997,2.1547,0
+2.3136,10.6651,-3.5288,-4.7672,0
+-1.8584,7.886,-1.6643,-1.8384,0
+3.106,9.5414,-4.2536,-4.003,0
+2.9163,10.8306,-3.3437,-4.122,0
+3.9922,-4.4676,3.7304,-0.1095,0
+1.518,5.6946,0.094818,-0.026738,0
+3.2351,9.647,-3.2074,-2.5948,0
+4.2188,6.8162,-1.2804,0.76076,0
+1.7819,6.9176,-1.2744,-1.5759,0
+2.5331,2.9135,-0.822,-0.12243,0
+3.8969,7.4163,-1.8245,0.14007,0
+2.108,6.7955,-0.1708,0.4905,0
+2.8969,0.70768,2.29,1.8663,0
+0.9297,-3.7971,4.6429,-0.2957,0
+3.4642,10.6878,-3.4071,-4.109,0
+4.0713,10.4023,-4.1722,-4.7582,0
+-1.4572,9.1214,1.7425,-5.1241,0
+-1.5075,1.9224,7.1466,0.89136,0
+-0.91718,9.9884,1.1804,-5.2263,0
+2.994,7.2011,-1.2153,0.3211,0
+-2.343,12.9516,3.3285,-5.9426,0
+3.7818,-2.8846,2.2558,-0.15734,0
+4.6689,1.3098,0.055404,1.909,0
+3.4663,1.1112,1.7425,1.3388,0
+3.2697,-4.3414,3.6884,-0.29829,0
+5.1302,8.6703,-2.8913,-1.5086,0
+2.0139,6.1416,0.37929,0.56938,0
+0.4339,5.5395,2.033,-0.40432,0
+-1.0401,9.3987,0.85998,-5.3336,0
+4.1605,11.2196,-3.6136,-4.0819,0
+5.438,9.4669,-4.9417,-3.9202,0
+5.032,8.2026,-2.6256,-1.0341,0
+5.2418,10.5388,-4.1174,-4.2797,0
+-0.2062,9.2207,-3.7044,-6.8103,0
+2.0911,0.94358,4.5512,1.234,0
+1.7317,-0.34765,4.1905,-0.99138,0
+4.1736,3.3336,-1.4244,0.60429,0
+3.9232,-3.2467,3.4579,0.83705,0
+3.8481,10.1539,-3.8561,-4.2228,0
+0.5195,-3.2633,3.0895,-0.9849,0
+3.8584,0.78425,1.1033,1.7008,0
+1.7496,-0.1759,5.1827,1.2922,0
+3.6277,0.9829,0.68861,0.63403,0
+2.7391,7.4018,0.071684,-2.5302,0
+4.5447,8.2274,-2.4166,-1.5875,0
+-1.7599,11.9211,2.6756,-3.3241,0
+5.0691,0.21313,0.20278,1.2095,0
+3.4591,11.112,-4.2039,-5.0931,0
+1.9358,8.1654,-0.023425,-2.2586,0
+2.486,-0.99533,5.3404,-0.15475,0
+2.4226,-4.5752,5.947,0.21507,0
+3.9479,-3.7723,2.883,0.019813,0
+2.2634,-4.4862,3.6558,-0.61251,0
+1.3566,4.2358,2.1341,0.3211,0
+5.0452,3.8964,-1.4304,0.86291,0
+3.5499,8.6165,-3.2794,-1.2009,0
+0.17346,7.8695,0.26876,-3.7883,0
+2.4008,9.3593,-3.3565,-3.3526,0
+4.8851,1.5995,-0.00029081,1.6401,0
+4.1927,-3.2674,2.5839,0.21766,0
+1.1166,8.6496,-0.96252,-1.8112,0
+1.0235,6.901,-2.0062,-2.7125,0
+-1.803,11.8818,2.0458,-5.2728,0
+0.11739,6.2761,-1.5495,-2.4746,0
+0.5706,-0.0248,1.2421,-0.5621,0
+4.0552,-2.4583,2.2806,1.0323,0
+-1.6952,1.0657,8.8294,0.94955,0
+-1.1193,10.7271,2.0938,-5.6504,0
+1.8799,2.4707,2.4931,0.37671,0
+3.583,-3.7971,3.4391,-0.12501,0
+0.19081,9.1297,-3.725,-5.8224,0
+3.6582,5.6864,-1.7157,-0.23751,0
+-0.13144,-1.7775,8.3316,0.35214,0
+2.3925,9.798,-3.0361,-2.8224,0
+1.6426,3.0149,0.22849,-0.147,0
+-0.11783,-1.5789,8.03,-0.028031,0
+-0.69572,8.6165,1.8419,-4.3289,0
+2.9421,7.4101,-0.97709,-0.88406,0
+-1.7559,11.9459,3.0946,-4.8978,0
+-1.2537,10.8803,1.931,-4.3237,0
+3.2585,-4.4614,3.8024,-0.15087,0
+1.8314,6.3672,-0.036278,0.049554,0
+4.5645,-3.6275,2.8684,0.27714,0
+2.7365,-5.0325,6.6608,-0.57889,0
+0.9297,-3.7971,4.6429,-0.2957,0
+3.9663,10.1684,-4.1131,-4.6056,0
+1.4578,-0.08485,4.1785,0.59136,0
+4.8272,3.0687,0.68604,0.80731,0
+-2.341,12.3784,0.70403,-7.5836,0
+-1.8584,7.886,-1.6643,-1.8384,0
+4.1454,7.257,-1.9153,-0.86078,0
+1.9157,6.0816,0.23705,-2.0116,0
+4.0215,-2.1914,2.4648,1.1409,0
+5.8862,5.8747,-2.8167,-0.30087,0
+-2.0897,10.8265,2.3603,-3.4198,0
+4.0026,-3.5943,3.5573,0.26809,0
+-0.78689,9.5663,-3.7867,-7.5034,0
+4.1757,10.2615,-3.8552,-4.3056,0
+0.83292,7.5404,0.65005,-0.92544,0
+4.8077,2.2327,-0.26334,1.5534,0
+5.3063,5.2684,-2.8904,-0.52716,0
+2.5605,9.2683,-3.5913,-1.356,0
+2.1059,7.6046,-0.47755,-1.8461,0
+2.1721,-0.73874,5.4672,-0.72371,0
+4.2899,9.1814,-4.6067,-4.3263,0
+3.5156,10.1891,-4.2759,-4.978,0
+2.614,8.0081,-3.7258,-1.3069,0
+0.68087,2.3259,4.9085,0.54998,0
+4.1962,0.74493,0.83256,0.753,0
+6.0919,2.9673,-1.3267,1.4551,0
+1.3234,3.2964,0.2362,-0.11984,0
+1.3264,1.0326,5.6566,-0.41337,0
+-0.16735,7.6274,1.2061,-3.6241,0
+-1.3,10.2678,-2.953,-5.8638,0
+-2.2261,12.5398,2.9438,-3.5258,0
+2.4196,6.4665,-0.75688,0.228,0
+1.0987,0.6394,5.989,-0.58277,0
+4.6464,10.5326,-4.5852,-4.206,0
+-0.36038,4.1158,3.1143,-0.37199,0
+1.3562,3.2136,4.3465,0.78662,0
+0.5706,-0.0248,1.2421,-0.5621,0
+-2.6479,10.1374,-1.331,-5.4707,0
+3.1219,-3.137,1.9259,-0.37458,0
+5.4944,1.5478,0.041694,1.9284,0
+-1.3389,1.552,7.0806,1.031,0
+-2.3361,11.9604,3.0835,-5.4435,0
+2.2596,-0.033118,4.7355,-0.2776,0
+0.46901,-0.63321,7.3848,0.36507,0
+2.7296,2.8701,0.51124,0.5099,0
+2.0466,2.03,2.1761,-0.083634,0
+-1.3274,9.498,2.4408,-5.2689,0
+3.8905,-2.1521,2.6302,1.1047,0
+3.9994,0.90427,1.1693,1.6892,0
+2.3952,9.5083,-3.1783,-3.0086,0
+3.2704,6.9321,-1.0456,0.23447,0
+-1.3931,1.5664,7.5382,0.78403,0
+1.6406,3.5488,1.3964,-0.36424,0
+2.7744,6.8576,-1.0671,0.075416,0
+2.4287,9.3821,-3.2477,-1.4543,0
+4.2134,-2.806,2.0116,0.67412,0
+1.6472,0.48213,4.7449,1.225,0
+2.0597,-0.99326,5.2119,-0.29312,0
+0.3798,0.7098,0.7572,-0.4444,0
+1.0135,8.4551,-1.672,-2.0815,0
+4.5691,-4.4552,3.1769,0.0042961,0
+0.57461,10.1105,-1.6917,-4.3922,0
+0.5734,9.1938,-0.9094,-1.872,0
+5.2868,3.257,-1.3721,1.1668,0
+4.0102,10.6568,-4.1388,-5.0646,0
+4.1425,-3.6792,3.8281,1.6297,0
+3.0934,-2.9177,2.2232,0.22283,0
+2.2034,5.9947,0.53009,0.84998,0
+3.744,0.79459,0.95851,1.0077,0
+3.0329,2.2948,2.1135,0.35084,0
+3.7731,7.2073,-1.6814,-0.94742,0
+3.1557,2.8908,0.59693,0.79825,0
+1.8114,7.6067,-0.9788,-2.4668,0
+4.988,7.2052,-3.2846,-1.1608,0
+2.483,6.6155,-0.79287,-0.90863,0
+1.594,4.7055,1.3758,0.081882,0
+-0.016103,9.7484,0.15394,-1.6134,0
+3.8496,9.7939,-4.1508,-4.4582,0
+0.9297,-3.7971,4.6429,-0.2957,0
+4.9342,2.4107,-0.17594,1.6245,0
+3.8417,10.0215,-4.2699,-4.9159,0
+5.3915,9.9946,-3.8081,-3.3642,0
+4.4072,-0.070365,2.0416,1.1319,0
+2.6946,6.7976,-0.40301,0.44912,0
+5.2756,0.13863,0.12138,1.1435,0
+3.4312,6.2637,-1.9513,-0.36165,0
+4.052,-0.16555,0.45383,0.51248,0
+1.3638,-4.7759,8.4182,-1.8836,0
+0.89566,7.7763,-2.7473,-1.9353,0
+1.9265,7.7557,-0.16823,-3.0771,0
+0.20977,-0.46146,7.7267,0.90946,0
+4.068,-2.9363,2.1992,0.50084,0
+2.877,-4.0599,3.6259,-0.32544,0
+0.3223,-0.89808,8.0883,0.69222,0
+-1.3,10.2678,-2.953,-5.8638,0
+1.7747,-6.4334,8.15,-0.89828,0
+1.3419,-4.4221,8.09,-1.7349,0
+0.89606,10.5471,-1.4175,-4.0327,0
+0.44125,2.9487,4.3225,0.7155,0
+3.2422,6.2265,0.12224,-1.4466,0
+2.5678,3.5136,0.61406,-0.40691,0
+-2.2153,11.9625,0.078538,-7.7853,0
+4.1349,6.1189,-2.4294,-0.19613,0
+1.934,-9.2828e-06,4.816,-0.33967,0
+2.5068,1.1588,3.9249,0.12585,0
+2.1464,6.0795,-0.5778,-2.2302,0
+0.051979,7.0521,-2.0541,-3.1508,0
+1.2706,8.035,-0.19651,-2.1888,0
+1.143,0.83391,5.4552,-0.56984,0
+2.2928,9.0386,-3.2417,-1.2991,0
+0.3292,-4.4552,4.5718,-0.9888,0
+2.9719,6.8369,-0.2702,0.71291,0
+1.6849,8.7489,-1.2641,-1.3858,0
+-1.9177,11.6894,2.5454,-3.2763,0
+2.3729,10.4726,-3.0087,-3.2013,0
+1.0284,9.767,-1.3687,-1.7853,0
+0.27451,9.2186,-3.2863,-4.8448,0
+1.6032,-4.7863,8.5193,-2.1203,0
+4.616,10.1788,-4.2185,-4.4245,0
+4.2478,7.6956,-2.7696,-1.0767,0
+4.0215,-2.7004,2.4957,0.36636,0
+5.0297,-4.9704,3.5025,-0.23751,0
+1.5902,2.2948,3.2403,0.18404,0
+2.1274,5.1939,-1.7971,-1.1763,0
+1.1811,8.3847,-2.0567,-0.90345,0
+0.3292,-4.4552,4.5718,-0.9888,0
+5.7353,5.2808,-2.2598,0.075416,0
+2.6718,5.6574,0.72974,-1.4892,0
+1.5799,-4.7076,7.9186,-1.5487,0
+2.9499,2.2493,1.3458,-0.037083,0
+0.5195,-3.2633,3.0895,-0.9849,0
+3.7352,9.5911,-3.9032,-3.3487,0
+-1.7344,2.0175,7.7618,0.93532,0
+3.884,10.0277,-3.9298,-4.0819,0
+3.5257,1.2829,1.9276,1.7991,0
+4.4549,2.4976,1.0313,0.96894,0
+-0.16108,-6.4624,8.3573,-1.5216,0
+4.2164,9.4607,-4.9288,-5.2366,0
+3.5152,6.8224,-0.67377,-0.46898,0
+1.6988,2.9094,2.9044,0.11033,0
+1.0607,2.4542,2.5188,-0.17027,0
+2.0421,1.2436,4.2171,0.90429,0
+3.5594,1.3078,1.291,1.6556,0
+3.0009,5.8126,-2.2306,-0.66553,0
+3.9294,1.4112,1.8076,0.89782,0
+3.4667,-4.0724,4.2882,1.5418,0
+3.966,3.9213,0.70574,0.33662,0
+1.0191,2.33,4.9334,0.82929,0
+0.96414,5.616,2.2138,-0.12501,0
+1.8205,6.7562,0.0099913,0.39481,0
+4.9923,7.8653,-2.3515,-0.71984,0
+-1.1804,11.5093,0.15565,-6.8194,0
+4.0329,0.23175,0.89082,1.1823,0
+0.66018,10.3878,-1.4029,-3.9151,0
+3.5982,7.1307,-1.3035,0.21248,0
+-1.8584,7.886,-1.6643,-1.8384,0
+4.0972,0.46972,1.6671,0.91593,0
+3.3299,0.91254,1.5806,0.39352,0
+3.1088,3.1122,0.80857,0.4336,0
+-4.2859,8.5234,3.1392,-0.91639,0
+-1.2528,10.2036,2.1787,-5.6038,0
+0.5195,-3.2633,3.0895,-0.9849,0
+0.3292,-4.4552,4.5718,-0.9888,0
+0.88872,5.3449,2.045,-0.19355,0
+3.5458,9.3718,-4.0351,-3.9564,0
+-0.21661,8.0329,1.8848,-3.8853,0
+2.7206,9.0821,-3.3111,-0.96811,0
+3.2051,8.6889,-2.9033,-0.7819,0
+2.6917,10.8161,-3.3,-4.2888,0
+-2.3242,11.5176,1.8231,-5.375,0
+2.7161,-4.2006,4.1914,0.16981,0
+3.3848,3.2674,0.90967,0.25128,0
+1.7452,4.8028,2.0878,0.62627,0
+2.805,0.57732,1.3424,1.2133,0
+5.7823,5.5788,-2.4089,-0.056479,0
+3.8999,1.734,1.6011,0.96765,0
+3.5189,6.332,-1.7791,-0.020273,0
+3.2294,7.7391,-0.37816,-2.5405,0
+3.4985,3.1639,0.22677,-0.1651,0
+2.1948,1.3781,1.1582,0.85774,0
+2.2526,9.9636,-3.1749,-2.9944,0
+4.1529,-3.9358,2.8633,-0.017686,0
+0.74307,11.17,-1.3824,-4.0728,0
+1.9105,8.871,-2.3386,-0.75604,0
+-1.5055,0.070346,6.8681,-0.50648,0
+0.58836,10.7727,-1.3884,-4.3276,0
+3.2303,7.8384,-3.5348,-1.2151,0
+-1.9922,11.6542,2.6542,-5.2107,0
+2.8523,9.0096,-3.761,-3.3371,0
+4.2772,2.4955,0.48554,0.36119,0
+1.5099,0.039307,6.2332,-0.30346,0
+5.4188,10.1457,-4.084,-3.6991,0
+0.86202,2.6963,4.2908,0.54739,0
+3.8117,10.1457,-4.0463,-4.5629,0
+0.54777,10.3754,-1.5435,-4.1633,0
+2.3718,7.4908,0.015989,-1.7414,0
+-2.4953,11.1472,1.9353,-3.4638,0
+4.6361,-2.6611,2.8358,1.1991,0
+-2.2527,11.5321,2.5899,-3.2737,0
+3.7982,10.423,-4.1602,-4.9728,0
+-0.36279,8.2895,-1.9213,-3.3332,0
+2.1265,6.8783,0.44784,-2.2224,0
+0.86736,5.5643,1.6765,-0.16769,0
+3.7831,10.0526,-3.8869,-3.7366,0
+-2.2623,12.1177,0.28846,-7.7581,0
+1.2616,4.4303,-1.3335,-1.7517,0
+2.6799,3.1349,0.34073,0.58489,0
+-0.39816,5.9781,1.3912,-1.1621,0
+4.3937,0.35798,2.0416,1.2004,0
+2.9695,5.6222,0.27561,-1.1556,0
+1.3049,-0.15521,6.4911,-0.75346,0
+2.2123,-5.8395,7.7687,-0.85302,0
+1.9647,6.9383,0.57722,0.66377,0
+3.0864,-2.5845,2.2309,0.30947,0
+0.3798,0.7098,0.7572,-0.4444,0
+0.58982,7.4266,1.2353,-2.9595,0
+0.14783,7.946,1.0742,-3.3409,0
+-0.062025,6.1975,1.099,-1.131,0
+4.223,1.1319,0.72202,0.96118,0
+0.64295,7.1018,0.3493,-0.41337,0
+1.941,0.46351,4.6472,1.0879,0
+4.0047,0.45937,1.3621,1.6181,0
+3.7767,9.7794,-3.9075,-3.5323,0
+3.4769,-0.15314,2.53,2.4495,0
+1.9818,9.2621,-3.521,-1.872,0
+3.8023,-3.8696,4.044,0.95343,0
+4.3483,11.1079,-4.0857,-4.2539,0
+1.1518,1.3864,5.2727,-0.43536,0
+-1.2576,1.5892,7.0078,0.42455,0
+1.9572,-5.1153,8.6127,-1.4297,0
+-2.484,12.1611,2.8204,-3.7418,0
+-1.1497,1.2954,7.701,0.62627,0
+4.8368,10.0132,-4.3239,-4.3276,0
+-0.12196,8.8068,0.94566,-4.2267,0
+1.9429,6.3961,0.092248,0.58102,0
+1.742,-4.809,8.2142,-2.0659,0
+-1.5222,10.8409,2.7827,-4.0974,0
+-1.3,10.2678,-2.953,-5.8638,0
+3.4246,-0.14693,0.80342,0.29136,0
+2.5503,-4.9518,6.3729,-0.41596,0
+1.5691,6.3465,-0.1828,-2.4099,0
+1.3087,4.9228,2.0013,0.22024,0
+5.1776,8.2316,-3.2511,-1.5694,0
+2.229,9.6325,-3.1123,-2.7164,0
+5.6272,10.0857,-4.2931,-3.8142,0
+1.2138,8.7986,-2.1672,-0.74182,0
+0.3798,0.7098,0.7572,-0.4444,0
+0.5415,6.0319,1.6825,-0.46122,0
+4.0524,5.6802,-1.9693,0.026279,0
+4.7285,2.1065,-0.28305,1.5625,0
+3.4359,0.66216,2.1041,1.8922,0
+0.86816,10.2429,-1.4912,-4.0082,0
+3.359,9.8022,-3.8209,-3.7133,0
+3.6702,2.9942,0.85141,0.30688,0
+1.3349,6.1189,0.46497,0.49826,0
+3.1887,-3.4143,2.7742,-0.2026,0
+2.4527,2.9653,0.20021,-0.056479,0
+3.9121,2.9735,0.92852,0.60558,0
+3.9364,10.5885,-3.725,-4.3133,0
+3.9414,-3.2902,3.1674,1.0866,0
+3.6922,-3.9585,4.3439,1.3517,0
+5.681,7.795,-2.6848,-0.92544,0
+0.77124,9.0862,-1.2281,-1.4996,0
+3.5761,9.7753,-3.9795,-3.4638,0
+1.602,6.1251,0.52924,0.47886,0
+2.6682,10.216,-3.4414,-4.0069,0
+2.0007,1.8644,2.6491,0.47369,0
+0.64215,3.1287,4.2933,0.64696,0
+4.3848,-3.0729,3.0423,1.2741,0
+0.77445,9.0552,-2.4089,-1.3884,0
+0.96574,8.393,-1.361,-1.4659,0
+3.0948,8.7324,-2.9007,-0.96682,0
+4.9362,7.6046,-2.3429,-0.85302,0
+-1.9458,11.2217,1.9079,-3.4405,0
+5.7403,-0.44284,0.38015,1.3763,0
+-2.6989,12.1984,0.67661,-8.5482,0
+1.1472,3.5985,1.9387,-0.43406,0
+2.9742,8.96,-2.9024,-1.0379,0
+4.5707,7.2094,-3.2794,-1.4944,0
+0.1848,6.5079,2.0133,-0.87242,0
+0.87256,9.2931,-0.7843,-2.1978,0
+0.39559,6.8866,1.0588,-0.67587,0
+3.8384,6.1851,-2.0439,-0.033204,0
+2.8209,7.3108,-0.81857,-1.8784,0
+2.5817,9.7546,-3.1749,-2.9957,0
+3.8213,0.23175,2.0133,2.0564,0
+0.3798,0.7098,0.7572,-0.4444,0
+3.4893,6.69,-1.2042,-0.38751,0
+-1.7781,0.8546,7.1303,0.027572,0
+2.0962,2.4769,1.9379,-0.040962,0
+0.94732,-0.57113,7.1903,-0.67587,0
+2.8261,9.4007,-3.3034,-1.0509,0
+0.0071249,8.3661,0.50781,-3.8155,0
+0.96788,7.1907,1.2798,-2.4565,0
+4.7432,2.1086,0.1368,1.6543,0
+3.6575,7.2797,-2.2692,-1.144,0
+3.8832,6.4023,-2.432,-0.98363,0
+3.4776,8.811,-3.1886,-0.92285,0
+1.1315,7.9212,1.093,-2.8444,0
+2.8237,2.8597,0.19678,0.57196,0
+1.9321,6.0423,0.26019,-2.053,0
+3.0632,-3.3315,5.1305,0.8267,0
+-1.8411,10.8306,2.769,-3.0901,0
+2.8084,11.3045,-3.3394,-4.4194,0
+2.5698,-4.4076,5.9856,0.078002,0
+-0.12624,10.3216,-3.7121,-6.1185,0
+3.3756,-4.0951,4.367,1.0698,0
+-0.048008,-1.6037,8.4756,0.75558,0
+0.5706,-0.0248,1.2421,-0.5621,0
+0.88444,6.5906,0.55837,-0.44182,0
+3.8644,3.7061,0.70403,0.35214,0
+1.2999,2.5762,2.0107,-0.18967,0
+2.0051,-6.8638,8.132,-0.2401,0
+4.9294,0.27727,0.20792,0.33662,0
+2.8297,6.3485,-0.73546,-0.58665,0
+2.565,8.633,-2.9941,-1.3082,0
+2.093,8.3061,0.022844,-3.2724,0
+4.6014,5.6264,-2.1235,0.19309,0
+5.0617,-0.35799,0.44698,0.99868,0
+-0.2951,9.0489,-0.52725,-2.0789,0
+3.577,2.4004,1.8908,0.73231,0
+3.9433,2.5017,1.5215,0.903,0
+2.6648,10.754,-3.3994,-4.1685,0
+5.9374,6.1664,-2.5905,-0.36553,0
+2.0153,1.8479,3.1375,0.42843,0
+5.8782,5.9409,-2.8544,-0.60863,0
+-2.3983,12.606,2.9464,-5.7888,0
+1.762,4.3682,2.1384,0.75429,0
+4.2406,-2.4852,1.608,0.7155,0
+3.4669,6.87,-1.0568,-0.73147,0
+3.1896,5.7526,-0.18537,-0.30087,0
+0.81356,9.1566,-2.1492,-4.1814,0
+0.52855,0.96427,4.0243,-1.0483,0
+2.1319,-2.0403,2.5574,-0.061652,0
+0.33111,4.5731,2.057,-0.18967,0
+1.2746,8.8172,-1.5323,-1.7957,0
+2.2091,7.4556,-1.3284,-3.3021,0
+2.5328,7.528,-0.41929,-2.6478,0
+3.6244,1.4609,1.3501,1.9284,0
+-1.3885,12.5026,0.69118,-7.5487,0
+5.7227,5.8312,-2.4097,-0.24527,0
+3.3583,10.3567,-3.7301,-3.6991,0
+2.5227,2.2369,2.7236,0.79438,0
+0.045304,6.7334,1.0708,-0.9332,0
+4.8278,7.7598,-2.4491,-1.2216,0
+1.9476,-4.7738,8.527,-1.8668,0
+2.7659,0.66216,4.1494,-0.28406,0
+-0.10648,-0.76771,7.7575,0.64179,0
+0.72252,-0.053811,5.6703,-1.3509,0
+4.2475,1.4816,-0.48355,0.95343,0
+3.9772,0.33521,2.2566,2.1625,0
+3.6667,4.302,0.55923,0.33791,0
+2.8232,10.8513,-3.1466,-3.9784,0
+-1.4217,11.6542,-0.057699,-7.1025,0
+4.2458,1.1981,0.66633,0.94696,0
+4.1038,-4.8069,3.3491,-0.49225,0
+1.4507,8.7903,-2.2324,-0.65259,0
+3.4647,-3.9172,3.9746,0.36119,0
+1.8533,6.1458,1.0176,-2.0401,0
+3.5288,0.71596,1.9507,1.9375,0
+3.9719,1.0367,0.75973,1.0013,0
+3.534,9.3614,-3.6316,-1.2461,0
+3.6894,9.887,-4.0788,-4.3664,0
+3.0672,-4.4117,3.8238,-0.81682,0
+2.6463,-4.8152,6.3549,0.003003,0
+2.2893,3.733,0.6312,-0.39786,0
+1.5673,7.9274,-0.056842,-2.1694,0
+4.0405,0.51524,1.0279,1.106,0
+4.3846,-4.8794,3.3662,-0.029324,0
+2.0165,-0.25246,5.1707,1.0763,0
+4.0446,11.1741,-4.3582,-4.7401,0
+-0.33729,-0.64976,7.6659,0.72326,0
+-2.4604,12.7302,0.91738,-7.6418,0
+4.1195,10.9258,-3.8929,-4.1802,0
+2.0193,0.82356,4.6369,1.4202,0
+1.5701,7.9129,0.29018,-2.1953,0
+2.6415,7.586,-0.28562,-1.6677,0
+5.0214,8.0764,-3.0515,-1.7155,0
+4.3435,3.3295,0.83598,0.64955,0
+1.8238,-6.7748,8.3873,-0.54139,0
+3.9382,0.9291,0.78543,0.6767,0
+2.2517,-5.1422,4.2916,-1.2487,0
+5.504,10.3671,-4.413,-4.0211,0
+2.8521,9.171,-3.6461,-1.2047,0
+1.1676,9.1566,-2.0867,-0.80647,0
+2.6104,8.0081,-0.23592,-1.7608,0
+0.32444,10.067,-1.1982,-4.1284,0
+3.8962,-4.7904,3.3954,-0.53751,0
+2.1752,-0.8091,5.1022,-0.67975,0
+1.1588,8.9331,-2.0807,-1.1272,0
+4.7072,8.2957,-2.5605,-1.4905,0
+-1.9667,11.8052,-0.40472,-7.8719,0
+4.0552,0.40143,1.4563,0.65343,0
+2.3678,-6.839,8.4207,-0.44829,0
+0.33565,6.8369,0.69718,-0.55691,0
+4.3398,-5.3036,3.8803,-0.70432,0
+1.5456,8.5482,0.4187,-2.1784,0
+1.4276,8.3847,-2.0995,-1.9677,0
+-0.27802,8.1881,-3.1338,-2.5276,0
+0.93611,8.6413,-1.6351,-1.3043,0
+4.6352,-3.0087,2.6773,1.212,0
+1.5268,-5.5871,8.6564,-1.722,0
+0.95626,2.4728,4.4578,0.21636,0
+-2.7914,1.7734,6.7756,-0.39915,0
+5.2032,3.5116,-1.2538,1.0129,0
+3.1836,7.2321,-1.0713,-2.5909,0
+0.65497,5.1815,1.0673,-0.42113,0
+5.6084,10.3009,-4.8003,-4.3534,0
+1.105,7.4432,0.41099,-3.0332,0
+3.9292,-2.9156,2.2129,0.30817,0
+1.1558,6.4003,1.5506,0.6961,0
+2.5581,2.6218,1.8513,0.40257,0
+2.7831,10.9796,-3.557,-4.4039,0
+3.7635,2.7811,0.66119,0.34179,0
+-2.6479,10.1374,-1.331,-5.4707,0
+1.0652,8.3682,-1.4004,-1.6509,0
+-1.4275,11.8797,0.41613,-6.9978,0
+5.7456,10.1808,-4.7857,-4.3366,0
+5.086,3.2798,-1.2701,1.1189,0
+3.4092,5.4049,-2.5228,-0.89958,0
+-0.2361,9.3221,2.1307,-4.3793,0
+3.8197,8.9951,-4.383,-4.0327,0
+-1.1391,1.8127,6.9144,0.70127,0
+4.9249,0.68906,0.77344,1.2095,0
+2.5089,6.841,-0.029423,0.44912,0
+-0.2062,9.2207,-3.7044,-6.8103,0
+3.946,6.8514,-1.5443,-0.5582,0
+-0.278,8.1881,-3.1338,-2.5276,0
+1.8592,3.2074,-0.15966,-0.26208,0
+0.56953,7.6294,1.5754,-3.2233,0
+3.4626,-4.449,3.5427,0.15429,0
+3.3951,1.1484,2.1401,2.0862,0
+5.0429,-0.52974,0.50439,1.106,0
+3.7758,7.1783,-1.5195,0.40128,0
+4.6562,7.6398,-2.4243,-1.2384,0
+4.0948,-2.9674,2.3689,0.75429,0
+1.8384,6.063,0.54723,0.51248,0
+2.0153,0.43661,4.5864,-0.3151,0
+3.5251,0.7201,1.6928,0.64438,0
+3.757,-5.4236,3.8255,-1.2526,0
+2.5989,3.5178,0.7623,0.81119,0
+1.8994,0.97462,4.2265,0.81377,0
+3.6941,-3.9482,4.2625,1.1577,0
+4.4295,-2.3507,1.7048,0.90946,0
+6.8248,5.2187,-2.5425,0.5461,0
+1.8967,-2.5163,2.8093,-0.79742,0
+2.1526,-6.1665,8.0831,-0.34355,0
+3.3004,7.0811,-1.3258,0.22283,0
+2.7213,7.05,-0.58808,0.41809,0
+3.8846,-3.0336,2.5334,0.20214,0
+4.1665,-0.4449,0.23448,0.27843,0
+0.94225,5.8561,1.8762,-0.32544,0
+5.1321,-0.031048,0.32616,1.1151,0
+0.38251,6.8121,1.8128,-0.61251,0
+3.0333,-2.5928,2.3183,0.303,0
+2.9233,6.0464,-0.11168,-0.58665,0
+1.162,10.2926,-1.2821,-4.0392,0
+3.7791,2.5762,1.3098,0.5655,0
+0.77765,5.9781,1.1941,-0.3526,0
+-0.38388,-1.0471,8.0514,0.49567,0
+0.21084,9.4359,-0.094543,-1.859,0
+2.9571,-4.5938,5.9068,0.57196,0
+4.6439,-3.3729,2.5976,0.55257,0
+3.3577,-4.3062,6.0241,0.18274,0
+3.5127,2.9073,1.0579,0.40774,0
+2.6562,10.7044,-3.3085,-4.0767,0
+-1.3612,10.694,1.7022,-2.9026,0
+-0.278,8.1881,-3.1338,-2.5276,0
+1.04,-6.9321,8.2888,-1.2991,0
+2.1881,2.7356,1.3278,-0.1832,0
+4.2756,-2.6528,2.1375,0.94437,0
+-0.11996,6.8741,0.91995,-0.6694,0
+2.9736,8.7944,-3.6359,-1.3754,0
+3.7798,-3.3109,2.6491,0.066365,0
+5.3586,3.7557,-1.7345,1.0789,0
+1.8373,6.1292,0.84027,0.55257,0
+1.2262,0.89599,5.7568,-0.11596,0
+-0.048008,-0.56078,7.7215,0.453,0
+0.5706,-0.024841,1.2421,-0.56208,0
+4.3634,0.46351,1.4281,2.0202,0
+3.482,-4.1634,3.5008,-0.078462,0
+0.51947,-3.2633,3.0895,-0.98492,0
+2.3164,-2.628,3.1529,-0.08622,0
+-1.8348,11.0334,3.1863,-4.8888,0
+1.3754,8.8793,-1.9136,-0.53751,0
+-0.16682,5.8974,0.49839,-0.70044,0
+0.29961,7.1328,-0.31475,-1.1828,0
+0.25035,9.3262,-3.6873,-6.2543,0
+2.4673,1.3926,1.7125,0.41421,0
+0.77805,6.6424,-1.1425,-1.0573,0
+3.4465,2.9508,1.0271,0.5461,0
+2.2429,-4.1427,5.2333,-0.40173,0
+3.7321,-3.884,3.3577,-0.0060486,0
+4.3365,-3.584,3.6884,0.74912,0
+-2.0759,10.8223,2.6439,-4.837,0
+4.0715,7.6398,-2.0824,-1.1698,0
+0.76163,5.8209,1.1959,-0.64613,0
+-0.53966,7.3273,0.46583,-1.4543,0
+2.6213,5.7919,0.065686,-1.5759,0
+3.0242,-3.3378,2.5865,-0.54785,0
+5.8519,5.3905,-2.4037,-0.061652,0
+0.5706,-0.0248,1.2421,-0.5621,0
+3.9771,11.1513,-3.9272,-4.3444,0
+1.5478,9.1814,-1.6326,-1.7375,0
+0.74054,0.36625,2.1992,0.48403,0
+0.49571,10.2243,-1.097,-4.0159,0
+1.645,7.8612,-0.87598,-3.5569,0
+3.6077,6.8576,-1.1622,0.28231,0
+3.2403,-3.7082,5.2804,0.41291,0
+3.9166,10.2491,-4.0926,-4.4659,0
+3.9262,6.0299,-2.0156,-0.065531,0
+5.591,10.4643,-4.3839,-4.3379,0
+3.7522,-3.6978,3.9943,1.3051,0
+1.3114,4.5462,2.2935,0.22541,0
+3.7022,6.9942,-1.8511,-0.12889,0
+4.364,-3.1039,2.3757,0.78532,0
+3.5829,1.4423,1.0219,1.4008,0
+4.65,-4.8297,3.4553,-0.25174,0
+5.1731,3.9606,-1.983,0.40774,0
+3.2692,3.4184,0.20706,-0.066824,0
+2.4012,1.6223,3.0312,0.71679,0
+1.7257,-4.4697,8.2219,-1.8073,0
+4.7965,6.9859,-1.9967,-0.35001,0
+4.0962,10.1891,-3.9323,-4.1827,0
+2.5559,3.3605,2.0321,0.26809,0
+3.4916,8.5709,-3.0326,-0.59182,0
+0.5195,-3.2633,3.0895,-0.9849,0
+2.9856,7.2673,-0.409,-2.2431,0
+4.0932,5.4132,-1.8219,0.23576,0
+1.7748,-0.76978,5.5854,1.3039,0
+5.2012,0.32694,0.17965,1.1797,0
+-0.45062,-1.3678,7.0858,-0.40303,0
+4.8451,8.1116,-2.9512,-1.4724,0
+0.74841,7.2756,1.1504,-0.5388,0
+5.1213,8.5565,-3.3917,-1.5474,0
+3.6181,-3.7454,2.8273,-0.71208,0
+0.040498,8.5234,1.4461,-3.9306,0
+-2.6479,10.1374,-1.331,-5.4707,0
+0.37984,0.70975,0.75716,-0.44441,0
+-0.95923,0.091039,6.2204,-1.4828,0
+2.8672,10.0008,-3.2049,-3.1095,0
+1.0182,9.109,-0.62064,-1.7129,0
+-2.7143,11.4535,2.1092,-3.9629,0
+3.8244,-3.1081,2.4537,0.52024,0
+2.7961,2.121,1.8385,0.38317,0
+3.5358,6.7086,-0.81857,0.47886,0
+-0.7056,8.7241,2.2215,-4.5965,0
+4.1542,7.2756,-2.4766,-1.2099,0
+0.92703,9.4318,-0.66263,-1.6728,0
+1.8216,-6.4748,8.0514,-0.41855,0
+-2.4473,12.6247,0.73573,-7.6612,0
+3.5862,-3.0957,2.8093,0.24481,0
+0.66191,9.6594,-0.28819,-1.6638,0
+4.7926,1.7071,-0.051701,1.4926,0
+4.9852,8.3516,-2.5425,-1.2823,0
+0.75736,3.0294,2.9164,-0.068117,0
+4.6499,7.6336,-1.9427,-0.37458,0
+-0.023579,7.1742,0.78457,-0.75734,0
+0.85574,0.0082678,6.6042,-0.53104,0
+0.88298,0.66009,6.0096,-0.43277,0
+4.0422,-4.391,4.7466,1.137,0
+2.2546,8.0992,-0.24877,-3.2698,0
+0.38478,6.5989,-0.3336,-0.56466,0
+3.1541,-5.1711,6.5991,0.57455,0
+2.3969,0.23589,4.8477,1.437,0
+4.7114,2.0755,-0.2702,1.2379,0
+4.0127,10.1477,-3.9366,-4.0728,0
+2.6606,3.1681,1.9619,0.18662,0
+3.931,1.8541,-0.023425,1.2314,0
+0.01727,8.693,1.3989,-3.9668,0
+3.2414,0.40971,1.4015,1.1952,0
+2.2504,3.5757,0.35273,0.2836,0
+-1.3971,3.3191,-1.3927,-1.9948,1
+0.39012,-0.14279,-0.031994,0.35084,1
+-1.6677,-7.1535,7.8929,0.96765,1
+-3.8483,-12.8047,15.6824,-1.281,1
+-3.5681,-8.213,10.083,0.96765,1
+-2.2804,-0.30626,1.3347,1.3763,1
+-1.7582,2.7397,-2.5323,-2.234,1
+-0.89409,3.1991,-1.8219,-2.9452,1
+0.3434,0.12415,-0.28733,0.14654,1
+-0.9854,-6.661,5.8245,0.5461,1
+-2.4115,-9.1359,9.3444,-0.65259,1
+-1.5252,-6.2534,5.3524,0.59912,1
+-0.61442,-0.091058,-0.31818,0.50214,1
+-0.36506,2.8928,-3.6461,-3.0603,1
+-5.9034,6.5679,0.67661,-6.6797,1
+-1.8215,2.7521,-0.72261,-2.353,1
+-0.77461,-1.8768,2.4023,1.1319,1
+-1.8187,-9.0366,9.0162,-0.12243,1
+-3.5801,-12.9309,13.1779,-2.5677,1
+-1.8219,-6.8824,5.4681,0.057313,1
+-0.3481,-0.38696,-0.47841,0.62627,1
+0.47368,3.3605,-4.5064,-4.0431,1
+-3.4083,4.8587,-0.76888,-4.8668,1
+-1.6662,-0.30005,1.4238,0.024986,1
+-2.0962,-7.1059,6.6188,-0.33708,1
+-2.6685,-10.4519,9.1139,-1.7323,1
+-0.47465,-4.3496,1.9901,0.7517,1
+1.0552,1.1857,-2.6411,0.11033,1
+1.1644,3.8095,-4.9408,-4.0909,1
+-4.4779,7.3708,-0.31218,-6.7754,1
+-2.7338,0.45523,2.4391,0.21766,1
+-2.286,-5.4484,5.8039,0.88231,1
+-1.6244,-6.3444,4.6575,0.16981,1
+0.50813,0.47799,-1.9804,0.57714,1
+1.6408,4.2503,-4.9023,-2.6621,1
+0.81583,4.84,-5.2613,-6.0823,1
+-5.4901,9.1048,-0.38758,-5.9763,1
+-3.2238,2.7935,0.32274,-0.86078,1
+-2.0631,-1.5147,1.219,0.44524,1
+-0.91318,-2.0113,-0.19565,0.066365,1
+0.6005,1.9327,-3.2888,-0.32415,1
+0.91315,3.3377,-4.0557,-1.6741,1
+-0.28015,3.0729,-3.3857,-2.9155,1
+-3.6085,3.3253,-0.51954,-3.5737,1
+-6.2003,8.6806,0.0091344,-3.703,1
+-4.2932,3.3419,0.77258,-0.99785,1
+-3.0265,-0.062088,0.68604,-0.055186,1
+-1.7015,-0.010356,-0.99337,-0.53104,1
+-0.64326,2.4748,-2.9452,-1.0276,1
+-0.86339,1.9348,-2.3729,-1.0897,1
+-2.0659,1.0512,-0.46298,-1.0974,1
+-2.1333,1.5685,-0.084261,-1.7453,1
+-1.2568,-1.4733,2.8718,0.44653,1
+-3.1128,-6.841,10.7402,-1.0172,1
+-4.8554,-5.9037,10.9818,-0.82199,1
+-2.588,3.8654,-0.3336,-1.2797,1
+0.24394,1.4733,-1.4192,-0.58535,1
+-1.5322,-5.0966,6.6779,0.17498,1
+-4.0025,-13.4979,17.6772,-3.3202,1
+-4.0173,-8.3123,12.4547,-1.4375,1
+-3.0731,-0.53181,2.3877,0.77627,1
+-1.979,3.2301,-1.3575,-2.5819,1
+-0.4294,-0.14693,0.044265,-0.15605,1
+-2.234,-7.0314,7.4936,0.61334,1
+-4.211,-12.4736,14.9704,-1.3884,1
+-3.8073,-8.0971,10.1772,0.65084,1
+-2.5912,-0.10554,1.2798,1.0414,1
+-2.2482,3.0915,-2.3969,-2.6711,1
+-1.4427,3.2922,-1.9702,-3.4392,1
+-0.39416,-0.020702,-0.066267,-0.44699,1
+-1.522,-6.6383,5.7491,-0.10691,1
+-2.8267,-9.0407,9.0694,-0.98233,1
+-1.7263,-6.0237,5.2419,0.29524,1
+-0.94255,0.039307,-0.24192,0.31593,1
+-0.89569,3.0025,-3.6067,-3.4457,1
+-6.2815,6.6651,0.52581,-7.0107,1
+-2.3211,3.166,-1.0002,-2.7151,1
+-1.3414,-2.0776,2.8093,0.60688,1
+-2.258,-9.3263,9.3727,-0.85949,1
+-3.8858,-12.8461,12.7957,-3.1353,1
+-1.8969,-6.7893,5.2761,-0.32544,1
+-0.52645,-0.24832,-0.45613,0.41938,1
+0.0096613,3.5612,-4.407,-4.4103,1
+-3.8826,4.898,-0.92311,-5.0801,1
+-2.1405,-0.16762,1.321,-0.20906,1
+-2.4824,-7.3046,6.839,-0.59053,1
+-2.9098,-10.0712,8.4156,-1.9948,1
+-0.60975,-4.002,1.8471,0.6017,1
+0.83625,1.1071,-2.4706,-0.062945,1
+0.60731,3.9544,-4.772,-4.4853,1
+-4.8861,7.0542,-0.17252,-6.959,1
+-3.1366,0.42212,2.6225,-0.064238,1
+-2.5754,-5.6574,6.103,0.65214,1
+-1.8782,-6.5865,4.8486,-0.021566,1
+0.24261,0.57318,-1.9402,0.44007,1
+1.296,4.2855,-4.8457,-2.9013,1
+0.25943,5.0097,-5.0394,-6.3862,1
+-5.873,9.1752,-0.27448,-6.0422,1
+-3.4605,2.6901,0.16165,-1.0224,1
+-2.3797,-1.4402,1.1273,0.16076,1
+-1.2424,-1.7175,-0.52553,-0.21036,1
+0.20216,1.9182,-3.2828,-0.61768,1
+0.59823,3.5012,-3.9795,-1.7841,1
+-0.77995,3.2322,-3.282,-3.1004,1
+-4.1409,3.4619,-0.47841,-3.8879,1
+-6.5084,8.7696,0.23191,-3.937,1
+-4.4996,3.4288,0.56265,-1.1672,1
+-3.3125,0.10139,0.55323,-0.2957,1
+-1.9423,0.3766,-1.2898,-0.82458,1
+-0.75793,2.5349,-3.0464,-1.2629,1
+-0.95403,1.9824,-2.3163,-1.1957,1
+-2.2173,1.4671,-0.72689,-1.1724,1
+-2.799,1.9679,-0.42357,-2.1125,1
+-1.8629,-0.84841,2.5377,0.097399,1
+-3.5916,-6.2285,10.2389,-1.1543,1
+-5.1216,-5.3118,10.3846,-1.0612,1
+-3.2854,4.0372,-0.45356,-1.8228,1
+-0.56877,1.4174,-1.4252,-1.1246,1
+-2.3518,-4.8359,6.6479,-0.060358,1
+-4.4861,-13.2889,17.3087,-3.2194,1
+-4.3876,-7.7267,11.9655,-1.4543,1
+-3.3604,-0.32696,2.1324,0.6017,1
+-1.0112,2.9984,-1.1664,-1.6185,1
+0.030219,-1.0512,1.4024,0.77369,1
+-1.6514,-8.4985,9.1122,1.2379,1
+-3.2692,-12.7406,15.5573,-0.14182,1
+-2.5701,-6.8452,8.9999,2.1353,1
+-1.3066,0.25244,0.7623,1.7758,1
+-1.6637,3.2881,-2.2701,-2.2224,1
+-0.55008,2.8659,-1.6488,-2.4319,1
+0.21431,-0.69529,0.87711,0.29653,1
+-0.77288,-7.4473,6.492,0.36119,1
+-1.8391,-9.0883,9.2416,-0.10432,1
+-0.63298,-5.1277,4.5624,1.4797,1
+0.0040545,0.62905,-0.64121,0.75817,1
+-0.28696,3.1784,-3.5767,-3.1896,1
+-5.2406,6.6258,-0.19908,-6.8607,1
+-1.4446,2.1438,-0.47241,-1.6677,1
+-0.65767,-2.8018,3.7115,0.99739,1
+-1.5449,-10.1498,9.6152,-1.2332,1
+-2.8957,-12.0205,11.9149,-2.7552,1
+-0.81479,-5.7381,4.3919,0.3211,1
+0.50225,0.65388,-1.1793,0.39998,1
+0.74521,3.6357,-4.4044,-4.1414,1
+-2.9146,4.0537,-0.45699,-4.0327,1
+-1.3907,-1.3781,2.3055,-0.021566,1
+-1.786,-8.1157,7.0858,-1.2112,1
+-1.7322,-9.2828,7.719,-1.7168,1
+0.55298,-3.4619,1.7048,1.1008,1
+2.031,1.852,-3.0121,0.003003,1
+1.2279,4.0309,-4.6435,-3.9125,1
+-4.2249,6.2699,0.15822,-5.5457,1
+-2.5346,-0.77392,3.3602,0.00171,1
+-1.749,-6.332,6.0987,0.14266,1
+-0.539,-5.167,3.4399,0.052141,1
+1.5631,0.89599,-1.9702,0.65472,1
+2.3917,4.5565,-4.9888,-2.8987,1
+0.89512,4.7738,-4.8431,-5.5909,1
+-5.4808,8.1819,0.27818,-5.0323,1
+-2.8833,1.7713,0.68946,-0.4638,1
+-1.4174,-2.2535,1.518,0.61981,1
+0.4283,-0.94981,-1.0731,0.3211,1
+1.5904,2.2121,-3.1183,-0.11725,1
+1.7425,3.6833,-4.0129,-1.7207,1
+-0.23356,3.2405,-3.0669,-2.7784,1
+-3.6227,3.9958,-0.35845,-3.9047,1
+-6.1536,7.9295,0.61663,-3.2646,1
+-3.9172,2.6652,0.78886,-0.7819,1
+-2.2214,-0.23798,0.56008,0.05602,1
+-0.49241,0.89392,-1.6283,-0.56854,1
+0.26517,2.4066,-2.8416,-0.59958,1
+-0.10234,1.8189,-2.2169,-0.56725,1
+-1.6176,1.0926,-0.35502,-0.59958,1
+-1.8448,1.254,0.27218,-1.0728,1
+-1.2786,-2.4087,4.5735,0.47627,1
+-2.902,-7.6563,11.8318,-0.84268,1
+-4.3773,-5.5167,10.939,-0.4082,1
+-2.0529,3.8385,-0.79544,-1.2138,1
+0.18868,0.70148,-0.51182,0.0055892,1
+-1.7279,-6.841,8.9494,0.68058,1
+-3.3793,-13.7731,17.9274,-2.0323,1
+-3.1273,-7.1121,11.3897,-0.083634,1
+-2.121,-0.05588,1.949,1.353,1
+-1.7697,3.4329,-1.2144,-2.3789,1
+-0.0012852,0.13863,-0.19651,0.0081754,1
+-1.682,-6.8121,7.1398,1.3323,1
+-3.4917,-12.1736,14.3689,-0.61639,1
+-3.1158,-8.6289,10.4403,0.97153,1
+-2.0891,-0.48422,1.704,1.7435,1
+-1.6936,2.7852,-2.1835,-1.9276,1
+-1.2846,3.2715,-1.7671,-3.2608,1
+-0.092194,0.39315,-0.32846,-0.13794,1
+-1.0292,-6.3879,5.5255,0.79955,1
+-2.2083,-9.1069,8.9991,-0.28406,1
+-1.0744,-6.3113,5.355,0.80472,1
+-0.51003,-0.23591,0.020273,0.76334,1
+-0.36372,3.0439,-3.4816,-2.7836,1
+-6.3979,6.4479,1.0836,-6.6176,1
+-2.2501,3.3129,-0.88369,-2.8974,1
+-1.1859,-1.2519,2.2635,0.77239,1
+-1.8076,-8.8131,8.7086,-0.21682,1
+-3.3863,-12.9889,13.0545,-2.7202,1
+-1.4106,-7.108,5.6454,0.31335,1
+-0.21394,-0.68287,0.096532,1.1965,1
+0.48797,3.5674,-4.3882,-3.8116,1
+-3.8167,5.1401,-0.65063,-5.4306,1
+-1.9555,0.20692,1.2473,-0.3707,1
+-2.1786,-6.4479,6.0344,-0.20777,1
+-2.3299,-9.9532,8.4756,-1.8733,1
+0.0031201,-4.0061,1.7956,0.91722,1
+1.3518,1.0595,-2.3437,0.39998,1
+1.2309,3.8923,-4.8277,-4.0069,1
+-5.0301,7.5032,-0.13396,-7.5034,1
+-3.0799,0.60836,2.7039,-0.23751,1
+-2.2987,-5.227,5.63,0.91722,1
+-1.239,-6.541,4.8151,-0.033204,1
+0.75896,0.29176,-1.6506,0.83834,1
+1.6799,4.2068,-4.5398,-2.3931,1
+0.63655,5.2022,-5.2159,-6.1211,1
+-6.0598,9.2952,-0.43642,-6.3694,1
+-3.518,2.8763,0.1548,-1.2086,1
+-2.0336,-1.4092,1.1582,0.36507,1
+-0.69745,-1.7672,-0.34474,-0.12372,1
+0.75108,1.9161,-3.1098,-0.20518,1
+0.84546,3.4826,-3.6307,-1.3961,1
+-0.55648,3.2136,-3.3085,-2.7965,1
+-3.6817,3.2239,-0.69347,-3.4004,1
+-6.7526,8.8172,-0.061983,-3.725,1
+-4.577,3.4515,0.66719,-0.94742,1
+-2.9883,0.31245,0.45041,0.068951,1
+-1.4781,0.14277,-1.1622,-0.48579,1
+-0.46651,2.3383,-2.9812,-1.0431,1
+-0.8734,1.6533,-2.1964,-0.78061,1
+-2.1234,1.1815,-0.55552,-0.81165,1
+-2.3142,2.0838,-0.46813,-1.6767,1
+-1.4233,-0.98912,2.3586,0.39481,1
+-3.0866,-6.6362,10.5405,-0.89182,1
+-4.7331,-6.1789,11.388,-1.0741,1
+-2.8829,3.8964,-0.1888,-1.1672,1
+-0.036127,1.525,-1.4089,-0.76121,1
+-1.7104,-4.778,6.2109,0.3974,1
+-3.8203,-13.0551,16.9583,-2.3052,1
+-3.7181,-8.5089,12.363,-0.95518,1
+-2.899,-0.60424,2.6045,1.3776,1
+-0.98193,2.7956,-1.2341,-1.5668,1
+-0.17296,-1.1816,1.3818,0.7336,1
+-1.9409,-8.6848,9.155,0.94049,1
+-3.5713,-12.4922,14.8881,-0.47027,1
+-2.9915,-6.6258,8.6521,1.8198,1
+-1.8483,0.31038,0.77344,1.4189,1
+-2.2677,3.2964,-2.2563,-2.4642,1
+-0.50816,2.868,-1.8108,-2.2612,1
+0.14329,-1.0885,1.0039,0.48791,1
+-0.90784,-7.9026,6.7807,0.34179,1
+-2.0042,-9.3676,9.3333,-0.10303,1
+-0.93587,-5.1008,4.5367,1.3866,1
+-0.40804,0.54214,-0.52725,0.6586,1
+-0.8172,3.3812,-3.6684,-3.456,1
+-4.8392,6.6755,-0.24278,-6.5775,1
+-1.2792,2.1376,-0.47584,-1.3974,1
+-0.66008,-3.226,3.8058,1.1836,1
+-1.7713,-10.7665,10.2184,-1.0043,1
+-3.0061,-12.2377,11.9552,-2.1603,1
+-1.1022,-5.8395,4.5641,0.68705,1
+0.11806,0.39108,-0.98223,0.42843,1
+0.11686,3.735,-4.4379,-4.3741,1
+-2.7264,3.9213,-0.49212,-3.6371,1
+-1.2369,-1.6906,2.518,0.51636,1
+-1.8439,-8.6475,7.6796,-0.66682,1
+-1.8554,-9.6035,7.7764,-0.97716,1
+0.16358,-3.3584,1.3749,1.3569,1
+1.5077,1.9596,-3.0584,-0.12243,1
+0.67886,4.1199,-4.569,-4.1414,1
+-3.9934,5.8333,0.54723,-4.9379,1
+-2.3898,-0.78427,3.0141,0.76205,1
+-1.7976,-6.7686,6.6753,0.89912,1
+-0.70867,-5.5602,4.0483,0.903,1
+1.0194,1.1029,-2.3,0.59395,1
+1.7875,4.78,-5.1362,-3.2362,1
+0.27331,4.8773,-4.9194,-5.8198,1
+-5.1661,8.0433,0.044265,-4.4983,1
+-2.7028,1.6327,0.83598,-0.091393,1
+-1.4904,-2.2183,1.6054,0.89394,1
+-0.014902,-1.0243,-0.94024,0.64955,1
+0.88992,2.2638,-3.1046,-0.11855,1
+1.0637,3.6957,-4.1594,-1.9379,1
+-0.8471,3.1329,-3.0112,-2.9388,1
+-3.9594,4.0289,-0.35845,-3.8957,1
+-5.8818,7.6584,0.5558,-2.9155,1
+-3.7747,2.5162,0.83341,-0.30993,1
+-2.4198,-0.24418,0.70146,0.41809,1
+-0.83535,0.80494,-1.6411,-0.19225,1
+-0.30432,2.6528,-2.7756,-0.65647,1
+-0.60254,1.7237,-2.1501,-0.77027,1
+-2.1059,1.1815,-0.53324,-0.82716,1
+-2.0441,1.2271,0.18564,-1.091,1
+-1.5621,-2.2121,4.2591,0.27972,1
+-3.2305,-7.2135,11.6433,-0.94613,1
+-4.8426,-4.9932,10.4052,-0.53104,1
+-2.3147,3.6668,-0.6969,-1.2474,1
+-0.11716,0.60422,-0.38587,-0.059065,1
+-2.0066,-6.719,9.0162,0.099985,1
+-3.6961,-13.6779,17.5795,-2.6181,1
+-3.6012,-6.5389,10.5234,-0.48967,1
+-2.6286,0.18002,1.7956,0.97282,1
+-0.82601,2.9611,-1.2864,-1.4647,1
+0.31803,-0.99326,1.0947,0.88619,1
+-1.4454,-8.4385,8.8483,0.96894,1
+-3.1423,-13.0365,15.6773,-0.66165,1
+-2.5373,-6.959,8.8054,1.5289,1
+-1.366,0.18416,0.90539,1.5806,1
+-1.7064,3.3088,-2.2829,-2.1978,1
+-0.41965,2.9094,-1.7859,-2.2069,1
+0.37637,-0.82358,0.78543,0.74524,1
+-0.55355,-7.9233,6.7156,0.74394,1
+-1.6001,-9.5828,9.4044,0.081882,1
+-0.37013,-5.554,4.7749,1.547,1
+0.12126,0.22347,-0.47327,0.97024,1
+-0.27068,3.2674,-3.5562,-3.0888,1
+-5.119,6.6486,-0.049987,-6.5206,1
+-1.3946,2.3134,-0.44499,-1.4905,1
+-0.69879,-3.3771,4.1211,1.5043,1
+-1.48,-10.5244,9.9176,-0.5026,1
+-2.6649,-12.813,12.6689,-1.9082,1
+-0.62684,-6.301,4.7843,1.106,1
+0.518,0.25865,-0.84085,0.96118,1
+0.64376,3.764,-4.4738,-4.0483,1
+-2.9821,4.1986,-0.5898,-3.9642,1
+-1.4628,-1.5706,2.4357,0.49826,1
+-1.7101,-8.7903,7.9735,-0.45475,1
+-1.5572,-9.8808,8.1088,-1.0806,1
+0.74428,-3.7723,1.6131,1.5754,1
+2.0177,1.7982,-2.9581,0.2099,1
+1.164,3.913,-4.5544,-3.8672,1
+-4.3667,6.0692,0.57208,-5.4668,1
+-2.5919,-1.0553,3.8949,0.77757,1
+-1.8046,-6.8141,6.7019,1.1681,1
+-0.71868,-5.7154,3.8298,1.0233,1
+1.4378,0.66837,-2.0267,1.0271,1
+2.1943,4.5503,-4.976,-2.7254,1
+0.7376,4.8525,-4.7986,-5.6659,1
+-5.637,8.1261,0.13081,-5.0142,1
+-3.0193,1.7775,0.73745,-0.45346,1
+-1.6706,-2.09,1.584,0.71162,1
+-0.1269,-1.1505,-0.95138,0.57843,1
+1.2198,2.0982,-3.1954,0.12843,1
+1.4501,3.6067,-4.0557,-1.5966,1
+-0.40857,3.0977,-2.9607,-2.6892,1
+-3.8952,3.8157,-0.31304,-3.8194,1
+-6.3679,8.0102,0.4247,-3.2207,1
+-4.1429,2.7749,0.68261,-0.71984,1
+-2.6864,-0.097265,0.61663,0.061192,1
+-1.0555,0.79459,-1.6968,-0.46768,1
+-0.29858,2.4769,-2.9512,-0.66165,1
+-0.49948,1.7734,-2.2469,-0.68104,1
+-1.9881,0.99945,-0.28562,-0.70044,1
+-1.9389,1.5706,0.045979,-1.122,1
+-1.4375,-1.8624,4.026,0.55127,1
+-3.1875,-7.5756,11.8678,-0.57889,1
+-4.6765,-5.6636,10.969,-0.33449,1
+-2.0285,3.8468,-0.63435,-1.175,1
+0.26637,0.73252,-0.67891,0.03533,1
+-1.7589,-6.4624,8.4773,0.31981,1
+-3.5985,-13.6593,17.6052,-2.4927,1
+-3.3582,-7.2404,11.4419,-0.57113,1
+-2.3629,-0.10554,1.9336,1.1358,1
+-2.1802,3.3791,-1.2256,-2.6621,1
+-0.40951,-0.15521,0.060545,-0.088807,1
+-2.2918,-7.257,7.9597,0.9211,1
+-4.0214,-12.8006,15.6199,-0.95647,1
+-3.3884,-8.215,10.3315,0.98187,1
+-2.0046,-0.49457,1.333,1.6543,1
+-1.7063,2.7956,-2.378,-2.3491,1
+-1.6386,3.3584,-1.7302,-3.5646,1
+-0.41645,0.32487,-0.33617,-0.36036,1
+-1.5877,-6.6072,5.8022,0.31593,1
+-2.5961,-9.349,9.7942,-0.28018,1
+-1.5228,-6.4789,5.7568,0.87325,1
+-0.53072,-0.097265,-0.21793,1.0426,1
+-0.49081,2.8452,-3.6436,-3.1004,1
+-6.5773,6.8017,0.85483,-7.5344,1
+-2.4621,2.7645,-0.62578,-2.8573,1
+-1.3995,-1.9162,2.5154,0.59912,1
+-2.3221,-9.3304,9.233,-0.79871,1
+-3.73,-12.9723,12.9817,-2.684,1
+-1.6988,-7.1163,5.7902,0.16723,1
+-0.26654,-0.64562,-0.42014,0.89136,1
+0.33325,3.3108,-4.5081,-4.012,1
+-4.2091,4.7283,-0.49126,-5.2159,1
+-2.3142,-0.68494,1.9833,-0.44829,1
+-2.4835,-7.4494,6.8964,-0.64484,1
+-2.7611,-10.5099,9.0239,-1.9547,1
+-0.36025,-4.449,2.1067,0.94308,1
+1.0117,0.9022,-2.3506,0.42714,1
+0.96708,3.8426,-4.9314,-4.1323,1
+-5.2049,7.259,0.070827,-7.3004,1
+-3.3203,-0.02691,2.9618,-0.44958,1
+-2.565,-5.7899,6.0122,0.046968,1
+-1.5951,-6.572,4.7689,-0.94354,1
+0.7049,0.17174,-1.7859,0.36119,1
+1.7331,3.9544,-4.7412,-2.5017,1
+0.6818,4.8504,-5.2133,-6.1043,1
+-6.3364,9.2848,0.014275,-6.7844,1
+-3.8053,2.4273,0.6809,-1.0871,1
+-2.1979,-2.1252,1.7151,0.45171,1
+-0.87874,-2.2121,-0.051701,0.099985,1
+0.74067,1.7299,-3.1963,-0.1457,1
+0.98296,3.4226,-3.9692,-1.7116,1
+-0.3489,3.1929,-3.4054,-3.1832,1
+-3.8552,3.5219,-0.38415,-3.8608,1
+-6.9599,8.9931,0.2182,-4.572,1
+-4.7462,3.1205,1.075,-1.2966,1
+-3.2051,-0.14279,0.97565,0.045675,1
+-1.7549,-0.080711,-0.75774,-0.3707,1
+-0.59587,2.4811,-2.8673,-0.89828,1
+-0.89542,2.0279,-2.3652,-1.2746,1
+-2.0754,1.2767,-0.64206,-1.2642,1
+-3.2778,1.8023,0.1805,-2.3931,1
+-2.2183,-1.254,2.9986,0.36378,1
+-3.5895,-6.572,10.5251,-0.16381,1
+-5.0477,-5.8023,11.244,-0.3901,1
+-3.5741,3.944,-0.07912,-2.1203,1
+-0.7351,1.7361,-1.4938,-1.1582,1
+-2.2617,-4.7428,6.3489,0.11162,1
+-4.244,-13.0634,17.1116,-2.8017,1
+-4.0218,-8.304,12.555,-1.5099,1
+-3.0201,-0.67253,2.7056,0.85774,1
+-2.4941,3.5447,-1.3721,-2.8483,1
+-0.83121,0.039307,0.05369,-0.23105,1
+-2.5665,-6.8824,7.5416,0.70774,1
+-4.4018,-12.9371,15.6559,-1.6806,1
+-3.7573,-8.2916,10.3032,0.38059,1
+-2.4725,-0.40145,1.4855,1.1189,1
+-1.9725,2.8825,-2.3086,-2.3724,1
+-2.0149,3.6874,-1.9385,-3.8918,1
+-0.82053,0.65181,-0.48869,-0.52716,1
+-1.7886,-6.3486,5.6154,0.42584,1
+-2.9138,-9.4711,9.7668,-0.60216,1
+-1.8343,-6.5907,5.6429,0.54998,1
+-0.8734,-0.033118,-0.20165,0.55774,1
+-0.70346,2.957,-3.5947,-3.1457,1
+-6.7387,6.9879,0.67833,-7.5887,1
+-2.7723,3.2777,-0.9351,-3.1457,1
+-1.6641,-1.3678,1.997,0.52283,1
+-2.4349,-9.2497,8.9922,-0.50001,1
+-3.793,-12.7095,12.7957,-2.825,1
+-1.9551,-6.9756,5.5383,-0.12889,1
+-0.69078,-0.50077,-0.35417,0.47498,1
+0.025013,3.3998,-4.4327,-4.2655,1
+-4.3967,4.9601,-0.64892,-5.4719,1
+-2.456,-0.24418,1.4041,-0.45863,1
+-2.62,-6.8555,6.2169,-0.62285,1
+-2.9662,-10.3257,8.784,-2.1138,1
+-0.71494,-4.4448,2.2241,0.49826,1
+0.6005,0.99945,-2.2126,0.097399,1
+0.61652,3.8944,-4.7275,-4.3948,1
+-5.4414,7.2363,0.10938,-7.5642,1
+-3.5798,0.45937,2.3457,-0.45734,1
+-2.7769,-5.6967,5.9179,0.37671,1
+-1.8356,-6.7562,5.0585,-0.55044,1
+0.30081,0.17381,-1.7542,0.48921,1
+1.3403,4.1323,-4.7018,-2.5987,1
+0.26877,4.987,-5.1508,-6.3913,1
+-6.5235,9.6014,-0.25392,-6.9642,1
+-4.0679,2.4955,0.79571,-1.1039,1
+-2.564,-1.7051,1.5026,0.32757,1
+-1.3414,-1.9162,-0.15538,-0.11984,1
+0.23874,2.0879,-3.3522,-0.66553,1
+0.6212,3.6771,-4.0771,-2.0711,1
+-0.77848,3.4019,-3.4859,-3.5569,1
+-4.1244,3.7909,-0.6532,-4.1802,1
+-7.0421,9.2,0.25933,-4.6832,1
+-4.9462,3.5716,0.82742,-1.4957,1
+-3.5359,0.30417,0.6569,-0.2957,1
+-2.0662,0.16967,-1.0054,-0.82975,1
+-0.88728,2.808,-3.1432,-1.2035,1
+-1.0941,2.3072,-2.5237,-1.4453,1
+-2.4458,1.6285,-0.88541,-1.4802,1
+-3.551,1.8955,0.1865,-2.4409,1
+-2.2811,-0.85669,2.7185,0.044382,1
+-3.6053,-5.974,10.0916,-0.82846,1
+-5.0676,-5.1877,10.4266,-0.86725,1
+-3.9204,4.0723,-0.23678,-2.1151,1
+-1.1306,1.8458,-1.3575,-1.3806,1
+-2.4561,-4.5566,6.4534,-0.056479,1
+-4.4775,-13.0303,17.0834,-3.0345,1
+-4.1958,-8.1819,12.1291,-1.6017,1
+-3.38,-0.7077,2.5325,0.71808,1
+-2.4365,3.6026,-1.4166,-2.8948,1
+-0.77688,0.13036,-0.031137,-0.35389,1
+-2.7083,-6.8266,7.5339,0.59007,1
+-4.5531,-12.5854,15.4417,-1.4983,1
+-3.8894,-7.8322,9.8208,0.47498,1
+-2.5084,-0.22763,1.488,1.2069,1
+-2.1652,3.0211,-2.4132,-2.4241,1
+-1.8974,3.5074,-1.7842,-3.8491,1
+-0.62043,0.5587,-0.38587,-0.66423,1
+-1.8387,-6.301,5.6506,0.19567,1
+-3,-9.1566,9.5766,-0.73018,1
+-1.9116,-6.1603,5.606,0.48533,1
+-1.005,0.084831,-0.2462,0.45688,1
+-0.87834,3.257,-3.6778,-3.2944,1
+-6.651,6.7934,0.68604,-7.5887,1
+-2.5463,3.1101,-0.83228,-3.0358,1
+-1.4377,-1.432,2.1144,0.42067,1
+-2.4554,-9.0407,8.862,-0.86983,1
+-3.9411,-12.8792,13.0597,-3.3125,1
+-2.1241,-6.8969,5.5992,-0.47156,1
+-0.74324,-0.32902,-0.42785,0.23317,1
+-0.071503,3.7412,-4.5415,-4.2526,1
+-4.2333,4.9166,-0.49212,-5.3207,1
+-2.3675,-0.43663,1.692,-0.43018,1
+-2.5526,-7.3625,6.9255,-0.66811,1
+-3.0986,-10.4602,8.9717,-2.3427,1
+-0.89809,-4.4862,2.2009,0.50731,1
+0.56232,1.0015,-2.2726,-0.0060486,1
+0.53936,3.8944,-4.8166,-4.3418,1
+-5.3012,7.3915,0.029699,-7.3987,1
+-3.3553,0.35591,2.6473,-0.37846,1
+-2.7908,-5.7133,5.953,0.45946,1
+-1.9983,-6.6072,4.8254,-0.41984,1
+0.15423,0.11794,-1.6823,0.59524,1
+1.208,4.0744,-4.7635,-2.6129,1
+0.2952,4.8856,-5.149,-6.2323,1
+-6.4247,9.5311,0.022844,-6.8517,1
+-3.9933,2.6218,0.62863,-1.1595,1
+-2.659,-1.6058,1.3647,0.16464,1
+-1.4094,-2.1252,-0.10397,-0.19225,1
+0.11032,1.9741,-3.3668,-0.65259,1
+0.52374,3.644,-4.0746,-1.9909,1
+-0.76794,3.4598,-3.4405,-3.4276,1
+-3.9698,3.6812,-0.60008,-4.0133,1
+-7.0364,9.2931,0.16594,-4.5396,1
+-4.9447,3.3005,1.063,-1.444,1
+-3.5933,0.22968,0.7126,-0.3332,1
+-2.1674,0.12415,-1.0465,-0.86208,1
+-0.9607,2.6963,-3.1226,-1.3121,1
+-1.0802,2.1996,-2.5862,-1.2759,1
+-2.3277,1.4381,-0.82114,-1.2862,1
+-3.7244,1.9037,-0.035421,-2.5095,1
+-2.5724,-0.95602,2.7073,-0.16639,1
+-3.9297,-6.0816,10.0958,-1.0147,1
+-5.2943,-5.1463,10.3332,-1.1181,1
+-3.8953,4.0392,-0.3019,-2.1836,1
+-1.2244,1.7485,-1.4801,-1.4181,1
+-2.6406,-4.4159,5.983,-0.13924,1
+-4.6338,-12.7509,16.7166,-3.2168,1
+-4.2887,-7.8633,11.8387,-1.8978,1
+-3.3458,-0.50491,2.6328,0.53705,1
+-1.1188,3.3357,-1.3455,-1.9573,1
+0.55939,-0.3104,0.18307,0.44653,1
+-1.5078,-7.3191,7.8981,1.2289,1
+-3.506,-12.5667,15.1606,-0.75216,1
+-2.9498,-8.273,10.2646,1.1629,1
+-1.6029,-0.38903,1.62,1.9103,1
+-1.2667,2.8183,-2.426,-1.8862,1
+-0.49281,3.0605,-1.8356,-2.834,1
+0.66365,-0.045533,-0.18794,0.23447,1
+-0.72068,-6.7583,5.8408,0.62369,1
+-1.9966,-9.5001,9.682,-0.12889,1
+-0.97325,-6.4168,5.6026,1.0323,1
+-0.025314,-0.17383,-0.11339,1.2198,1
+0.062525,2.9301,-3.5467,-2.6737,1
+-5.525,6.3258,0.89768,-6.6241,1
+-1.2943,2.6735,-0.84085,-2.0323,1
+-0.24037,-1.7837,2.135,1.2418,1
+-1.3968,-9.6698,9.4652,-0.34872,1
+-2.9672,-13.2869,13.4727,-2.6271,1
+-1.1005,-7.2508,6.0139,0.36895,1
+0.22432,-0.52147,-0.40386,1.2017,1
+0.90407,3.3708,-4.4987,-3.6965,1
+-2.8619,4.5193,-0.58123,-4.2629,1
+-1.0833,-0.31247,1.2815,0.41291,1
+-1.5681,-7.2446,6.5537,-0.1276,1
+-2.0545,-10.8679,9.4926,-1.4116,1
+0.2346,-4.5152,2.1195,1.4448,1
+1.581,0.86909,-2.3138,0.82412,1
+1.5514,3.8013,-4.9143,-3.7483,1
+-4.1479,7.1225,-0.083404,-6.4172,1
+-2.2625,-0.099335,2.8127,0.48662,1
+-1.7479,-5.823,5.8699,1.212,1
+-0.95923,-6.7128,4.9857,0.32886,1
+1.3451,0.23589,-1.8785,1.3258,1
+2.2279,4.0951,-4.8037,-2.1112,1
+1.2572,4.8731,-5.2861,-5.8741,1
+-5.3857,9.1214,-0.41929,-5.9181,1
+-2.9786,2.3445,0.52667,-0.40173,1
+-1.5851,-2.1562,1.7082,0.9017,1
+-0.21888,-2.2038,-0.0954,0.56421,1
+1.3183,1.9017,-3.3111,0.065071,1
+1.4896,3.4288,-4.0309,-1.4259,1
+0.11592,3.2219,-3.4302,-2.8457,1
+-3.3924,3.3564,-0.72004,-3.5233,1
+-6.1632,8.7096,-0.21621,-3.6345,1
+-4.0786,2.9239,0.87026,-0.65389,1
+-2.5899,-0.3911,0.93452,0.42972,1
+-1.0116,-0.19038,-0.90597,0.003003,1
+0.066129,2.4914,-2.9401,-0.62156,1
+-0.24745,1.9368,-2.4697,-0.80518,1
+-1.5732,1.0636,-0.71232,-0.8388,1
+-2.1668,1.5933,0.045122,-1.678,1
+-1.1667,-1.4237,2.9241,0.66119,1
+-2.8391,-6.63,10.4849,-0.42113,1
+-4.5046,-5.8126,10.8867,-0.52846,1
+-2.41,3.7433,-0.40215,-1.2953,1
+0.40614,1.3492,-1.4501,-0.55949,1
+-1.3887,-4.8773,6.4774,0.34179,1
+-3.7503,-13.4586,17.5932,-2.7771,1
+-3.5637,-8.3827,12.393,-1.2823,1
+-2.5419,-0.65804,2.6842,1.1952,1
\ No newline at end of file
diff --git a/doc/src/week44/DataFiles/cancer.dot b/doc/src/week44/DataFiles/cancer.dot
new file mode 100644
index 000000000..5b4b48a9b
--- /dev/null
+++ b/doc/src/week44/DataFiles/cancer.dot
@@ -0,0 +1,57 @@
+digraph Tree {
+node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ;
+edge [fontname=helvetica] ;
+0 [label="worst perimeter <= 106.05\ngini = 0.465\nsamples = 426\nvalue = [[269, 157]\n[157, 269]]", fillcolor="#e5813908"] ;
+1 [label="worst concave points <= 0.159\ngini = 0.067\nsamples = 259\nvalue = [[250, 9]\n[9, 250]]", fillcolor="#e58139db"] ;
+0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
+2 [label="worst concave points <= 0.135\ngini = 0.031\nsamples = 253\nvalue = [[249, 4]\n[4, 249]]", fillcolor="#e58139ee"] ;
+1 -> 2 ;
+3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e58139fb"] ;
+2 -> 3 ;
+4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139ff"] ;
+3 -> 4 ;
+5 [label="worst symmetry <= 0.208\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ;
+3 -> 5 ;
+6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139ff"] ;
+5 -> 6 ;
+7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ;
+5 -> 7 ;
+8 [label="worst texture <= 29.455\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#e581392c"] ;
+2 -> 8 ;
+9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139ff"] ;
+8 -> 9 ;
+10 [label="gini = 0.0\nsamples = 3\nvalue = [[0, 3]\n[3, 0]]", fillcolor="#e58139ff"] ;
+8 -> 10 ;
+11 [label="mean texture <= 16.22\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ;
+1 -> 11 ;
+12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
+11 -> 12 ;
+13 [label="gini = 0.0\nsamples = 5\nvalue = [[0, 5]\n[5, 0]]", fillcolor="#e58139ff"] ;
+11 -> 13 ;
+14 [label="worst texture <= 20.645\ngini = 0.202\nsamples = 167\nvalue = [[19, 148]\n[148, 19]]", fillcolor="#e5813994"] ;
+0 -> 14 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
+15 [label="worst radius <= 17.74\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ;
+14 -> 15 ;
+16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139ff"] ;
+15 -> 16 ;
+17 [label="mean texture <= 13.745\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ;
+15 -> 17 ;
+18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
+17 -> 18 ;
+19 [label="gini = 0.0\nsamples = 4\nvalue = [[0, 4]\n[4, 0]]", fillcolor="#e58139ff"] ;
+17 -> 19 ;
+20 [label="mean concave points <= 0.049\ngini = 0.088\nsamples = 151\nvalue = [[7, 144]\n[144, 7]]", fillcolor="#e58139d0"] ;
+14 -> 20 ;
+21 [label="concave points error <= 0.01\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#e5813900"] ;
+20 -> 21 ;
+22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139ff"] ;
+21 -> 22 ;
+23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139ff"] ;
+21 -> 23 ;
+24 [label="worst smoothness <= 0.096\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e58139f7"] ;
+20 -> 24 ;
+25 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
+24 -> 25 ;
+26 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139ff"] ;
+24 -> 26 ;
+}
\ No newline at end of file
diff --git a/doc/src/week44/DataFiles/cancer.png b/doc/src/week44/DataFiles/cancer.png
new file mode 100644
index 000000000..2ceb5e1f8
Binary files /dev/null and b/doc/src/week44/DataFiles/cancer.png differ
diff --git a/doc/src/week44/DataFiles/ensembleoverview.png b/doc/src/week44/DataFiles/ensembleoverview.png
new file mode 100644
index 000000000..dce581ee6
Binary files /dev/null and b/doc/src/week44/DataFiles/ensembleoverview.png differ
diff --git a/doc/src/week44/DataFiles/ride.csv b/doc/src/week44/DataFiles/ride.csv
new file mode 100644
index 000000000..d03d4ca16
--- /dev/null
+++ b/doc/src/week44/DataFiles/ride.csv
@@ -0,0 +1,15 @@
+Outlook,Temperature,Humidity,Wind,Ride
+0,0,0,0,0
+0,0,0,1,1
+1,0,0,0,1
+2,1,0,0,1
+2,2,1,0,1
+2,2,1,1,0
+1,2,1,1,1
+0,1,0,0,0
+0,2,1,0,1
+2,1,1,0,1
+0,1,1,1,1
+1,1,0,1,1
+1,0,1,0,1
+2,1,0,1,0
diff --git a/doc/src/week44/DataFiles/ride.csv~ b/doc/src/week44/DataFiles/ride.csv~
new file mode 100644
index 000000000..7a908c5f7
--- /dev/null
+++ b/doc/src/week44/DataFiles/ride.csv~
@@ -0,0 +1,15 @@
+Outlook,Temperature,Humidity,Wind,Ride
+Sunny,Hot,High,Weak,0
+Sunny,Hot,High,Strong,1
+Overcast,Hot,High,Weak,1
+Rain,Mild,High,Weak,1
+Rain,Cool,Normal,Weak,1
+Rain,Cool,Normal,Strong,0
+Overcast,Cool,Normal,Strong,1
+Sunny,Mild,High,Weak,0
+Sunny,Cool,Normal,Weak,1
+Rain,Mild,Normal,Weak,1
+Sunny,Mild,Normal,Strong,1
+Overcast,Mild,High,Strong,1
+Overcast,Hot,Normal,Weak,1
+Rain,Mild,High,Strong,0
diff --git a/doc/src/week44/DataFiles/ride.dot b/doc/src/week44/DataFiles/ride.dot
new file mode 100644
index 000000000..50aaa7638
--- /dev/null
+++ b/doc/src/week44/DataFiles/ride.dot
@@ -0,0 +1,13 @@
+digraph Tree {
+node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ;
+edge [fontname=helvetica] ;
+0 [label="X[7] <= 0.5\ngini = 0.48\nsamples = 15\nvalue = [4, 10, 1]", fillcolor="#39e5818b"] ;
+1 [label="X[1] <= 0.5\ngini = 0.408\nsamples = 14\nvalue = [4, 10, 0]", fillcolor="#39e58199"] ;
+0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
+2 [label="gini = 0.48\nsamples = 10\nvalue = [4, 6, 0]", fillcolor="#39e58155"] ;
+1 -> 2 ;
+3 [label="gini = 0.0\nsamples = 4\nvalue = [0, 4, 0]", fillcolor="#39e581ff"] ;
+1 -> 3 ;
+4 [label="gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]", fillcolor="#8139e5ff"] ;
+0 -> 4 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
+}
\ No newline at end of file
diff --git a/doc/src/week44/DataFiles/rideclass.csv b/doc/src/week44/DataFiles/rideclass.csv
new file mode 100644
index 000000000..a0831ac7e
--- /dev/null
+++ b/doc/src/week44/DataFiles/rideclass.csv
@@ -0,0 +1,15 @@
+Day,Outlook,Temperature,Humidity,Wind,Ride
+1,Sunny,Hot,High,Weak,0
+2,Sunny,Hot,High,Strong,1
+3,Overcast,Hot,High,Weak,1
+4,Rain,Mild,High,Weak,1
+5,Rain,Cool,Normal,Weak,1
+6,Rain,Cool,Normal,Strong,0
+7,Overcast,Cool,Normal,Strong,1
+8,Sunny,Mild,High,Weak,0
+9,Sunny,Cool,Normal,Weak,1
+10,Rain,Mild,Normal,Weak,1
+11,Sunny,Mild,Normal,Strong,1
+12,Overcast,Mild,High,Strong,1
+13,Overcast,Hot,Normal,Weak,1
+14,Rain,Mild,High,Strong,0
diff --git a/doc/src/week44/DataFiles/zoo.csv b/doc/src/week44/DataFiles/zoo.csv
new file mode 100644
index 000000000..ca71f7d21
--- /dev/null
+++ b/doc/src/week44/DataFiles/zoo.csv
@@ -0,0 +1,101 @@
+aardvark,1,0,0,1,0,0,1,1,1,1,0,0,4,0,0,1,1
+antelope,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+bass,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
+bear,1,0,0,1,0,0,1,1,1,1,0,0,4,0,0,1,1
+boar,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+buffalo,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+calf,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
+carp,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,4
+catfish,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
+cavy,1,0,0,1,0,0,0,1,1,1,0,0,4,0,1,0,1
+cheetah,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+chicken,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
+chub,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
+clam,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,7
+crab,0,0,1,0,0,1,1,0,0,0,0,0,4,0,0,0,7
+crayfish,0,0,1,0,0,1,1,0,0,0,0,0,6,0,0,0,7
+crow,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,0,2
+deer,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+dogfish,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
+dolphin,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1
+dove,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
+duck,0,1,1,0,1,1,0,0,1,1,0,0,2,1,0,0,2
+elephant,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+flamingo,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,1,2
+flea,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
+frog,0,0,1,0,0,1,1,1,1,1,0,0,4,0,0,0,5
+frog,0,0,1,0,0,1,1,1,1,1,1,0,4,0,0,0,5
+fruitbat,1,0,0,1,1,0,0,1,1,1,0,0,2,1,0,0,1
+giraffe,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+girl,1,0,0,1,0,0,1,1,1,1,0,0,2,0,1,1,1
+gnat,0,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
+goat,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
+gorilla,1,0,0,1,0,0,0,1,1,1,0,0,2,0,0,1,1
+gull,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
+haddock,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
+hamster,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,0,1
+hare,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,0,1
+hawk,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,0,2
+herring,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
+honeybee,1,0,1,0,1,0,0,0,0,1,1,0,6,0,1,0,6
+housefly,1,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
+kiwi,0,1,1,0,0,0,1,0,1,1,0,0,2,1,0,0,2
+ladybird,0,0,1,0,1,0,1,0,0,1,0,0,6,0,0,0,6
+lark,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
+leopard,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+lion,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+lobster,0,0,1,0,0,1,1,0,0,0,0,0,6,0,0,0,7
+lynx,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+mink,1,0,0,1,0,1,1,1,1,1,0,0,4,1,0,1,1
+mole,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,0,1
+mongoose,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+moth,1,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
+newt,0,0,1,0,0,1,1,1,1,1,0,0,4,1,0,0,5
+octopus,0,0,1,0,0,1,1,0,0,0,0,0,8,0,0,1,7
+opossum,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,0,1
+oryx,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
+ostrich,0,1,1,0,0,0,0,0,1,1,0,0,2,1,0,1,2
+parakeet,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
+penguin,0,1,1,0,0,1,1,0,1,1,0,0,2,1,0,1,2
+pheasant,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
+pike,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
+piranha,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
+pitviper,0,0,1,0,0,0,1,1,1,1,1,0,0,1,0,0,3
+platypus,1,0,1,1,0,1,1,0,1,1,0,0,4,1,0,1,1
+polecat,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+pony,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
+porpoise,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1
+puma,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+pussycat,1,0,0,1,0,0,1,1,1,1,0,0,4,1,1,1,1
+raccoon,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+reindeer,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
+rhea,0,1,1,0,0,0,1,0,1,1,0,0,2,1,0,1,2
+scorpion,0,0,0,0,0,0,1,0,0,1,1,0,8,1,0,0,7
+seahorse,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
+seal,1,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,1
+sealion,1,0,0,1,0,1,1,1,1,1,0,1,2,1,0,1,1
+seasnake,0,0,0,0,0,1,1,1,1,0,1,0,0,1,0,0,3
+seawasp,0,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,7
+skimmer,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
+skua,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
+slowworm,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,0,3
+slug,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,7
+sole,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
+sparrow,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
+squirrel,1,0,0,1,0,0,0,1,1,1,0,0,2,1,0,0,1
+starfish,0,0,1,0,0,1,1,0,0,0,0,0,5,0,0,0,7
+stingray,0,0,1,0,0,1,1,1,1,0,1,1,0,1,0,1,4
+swan,0,1,1,0,1,1,0,0,1,1,0,0,2,1,0,1,2
+termite,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
+toad,0,0,1,0,0,1,0,1,1,1,0,0,4,0,0,0,5
+tortoise,0,0,1,0,0,0,0,0,1,1,0,0,4,1,0,1,3
+tuatara,0,0,1,0,0,0,1,1,1,1,0,0,4,1,0,0,3
+tuna,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
+vampire,1,0,0,1,1,0,0,1,1,1,0,0,2,1,0,0,1
+vole,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,0,1
+vulture,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,1,2
+wallaby,1,0,0,1,0,0,0,1,1,1,0,0,2,1,0,1,1
+wasp,1,0,1,0,1,0,0,0,0,1,1,0,6,0,0,0,6
+wolf,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
+worm,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,7
+wren,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
diff --git a/doc/src/week44/week44.do.txt b/doc/src/week44/week44.do.txt
new file mode 100644
index 000000000..c2265f811
--- /dev/null
+++ b/doc/src/week44/week44.do.txt
@@ -0,0 +1,1524 @@
+TITLE: week 44: From Decision Trees to Bagging methods
+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
+
+
+!split
+===== Decision trees, overarching aims =====
+
+
+We start here with the most basic algorithm, the so-called decision
+tree. With this basic algorithm we can in turn build more complex
+networks, spanning from homogeneous and heterogenous forests (bagging,
+random forests and more) to one of the most popular supervised
+algorithms nowadays, the extreme gradient boosting, or just
+XGBoost. But let us start with the simplest possible ingredient.
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+_information_ regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the _most
+informative_ feature is done until we accomplish a stopping criteria
+where we then finally end up in so called _leaf nodes_.
+
+
+
+A decision tree is typically divided into a _root node_, the _interior nodes_,
+and the final _leaf nodes_ or just _leaves_. These entities are then connected by so-called _branches_.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+!split
+===== A typical Decision Tree with its pertinent Jargon, Classification Problem =====
+
+FIGURE: [DataFiles/cancer.png, width=600 frac=0.8]
+
+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using _Scikit-Learn_'s decision tree classifier. Here we have used the so-called _gini_ index (see below) to split the various branches.
+
+
+
+!split
+===== General Features =====
+
+The overarching approach to decision trees is a top-down approach.
+
+* A leaf provides the classification of a given instance.
+* A node specifies a test of some attribute of the instance.
+* A branch corresponds to a possible values of an attribute.
+* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+!split
+===== How do we set it up? =====
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+o Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+o Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+o Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances
+
+o Show query instances to the tree and run down the tree until we arrive at leaf nodes
+
+Then we are essentially done!
+
+
+
+
+
+!split
+===== Decision trees and Regression =====
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0 and bestAttrId in attributeIds:
+ toRemove = attributeIds.index(bestAttrId)
+ attributeIds.pop(toRemove)
+ child.next = self.id3Recv(
+ childSampleIds, attributeIds, child.next)
+ return root
+
+ def printTree(self):
+ if self.root:
+ roots = deque()
+ roots.append(self.root)
+ while len(roots) > 0:
+ root = roots.popleft()
+ print(root.value)
+ if root.childs:
+ for child in root.childs:
+ print('({})'.format(child.value))
+ roots.append(child.next)
+ elif root.next:
+ print(root.next)
+
+
+def test():
+ f = open('DataFiles/rideclass.csv')
+ attributes = f.readline().split(',')
+ attributes = attributes[1:len(attributes)-1]
+ print(attributes)
+ sample = f.readlines()
+ f.close()
+ for i in range(len(sample)):
+ sample[i] = re.sub('\d+,', '', sample[i])
+ sample[i] = sample[i].strip().split(',')
+ labels = []
+ for s in sample:
+ labels.append(s.pop())
+ # print(sample)
+ # print(labels)
+ decisionTree = DecisionTree(sample, attributes, labels)
+ print("System entropy {}".format(decisionTree.entropy))
+ decisionTree.id3()
+ decisionTree.printTree()
+
+
+if __name__ == '__main__':
+ test()
+!ec
+
+!split
+===== Cancer Data again now with Decision Trees and other Methods =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+!ec
+
+
+!split
+===== Another example, the moons again =====
+!bc pycod
+from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if not iris:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ if plot_training:
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+ plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+ plt.axis(axes)
+ if iris:
+ plt.xlabel("Petal length", fontsize=14)
+ plt.ylabel("Petal width", fontsize=14)
+ else:
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+ if legend:
+ plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+!ec
+
+!split
+===== Playing around with regions =====
+!bc pycod
+np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+!ec
+
+!split
+===== Regression trees =====
+!bc pycod
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+!ec
+
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+!ec
+
+!split
+===== Final regressor code =====
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+!ec
+
+!bc pycod
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+!ec
+
+
+
+!split
+===== Pros and cons of trees, pros =====
+
+* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+* No feature normalization needed
+* Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+* Can model nonlinear relationships
+* Can model interactions between the different descriptive features
+* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+!split
+===== Disadvantages =====
+
+* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+* If continuous features are used the tree may become quite large and hence less interpretable
+* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+
+
+!split
+===== Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods =====
+
+As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+
+This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+
+o Voting classifiers
+o Bagging and Pasting
+o Random forests
+o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+
+We discuss these methods here.
+
+
+!split
+===== An Overview of Ensemble Methods =====
+
+FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8]
+
+
+
+!split
+===== Bagging =====
+
+The _plain_ decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+_Bootstrap aggregation_, or just _bagging_, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+!split
+===== More bagging =====
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+!split
+===== Simple Voting Example, head or tail =====
+!bc pycod
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+!ec
+
+!split
+===== Using the Voting Classifier =====
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+!ec
+
+!split
+===== Please, not the moons again! Voting and Bagging =====
+
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+!split
+===== Bagging Examples =====
+
+!bc pycod
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+!ec
+
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+!ec
+
+!bc pycod
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+!ec
+
+
+
+!split
+===== Making your own Bootstrap: Changing the Level of the Decision Tree =====
+
+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
+a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$).
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+!ec
+
+
diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt
new file mode 100644
index 000000000..13c6037d4
--- /dev/null
+++ b/doc/src/week45/week45.do.txt
@@ -0,0 +1,815 @@
+TITLE: Week 45: Random Forests and Boosting
+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
+
+
+
+!split
+===== Random forests =====
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+!bt
+\[
+m\approx \sqrt{p}.
+\]
+!et
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quantities. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+!split
+===== Random Forest Algorithm =====
+The algorithm described here can be applied to both classification and regression problems.
+
+We will grow of forest of say $B$ trees.
+o For $b=1:B$
+ * Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix.
+ * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
+ o we select $m \le p$ variables at random from the $p$ predictors/features
+ o pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node
+ o split the node into daughter nodes
+o Output then the ensemble of trees $\{T_b\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem.
+
+
+
+!split
+===== Random Forests Compared with other Methods on the Cancer Data =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+!ec
+
+
+!split
+===== Compare Bagging on Trees with Random Forests =====
+!bc pycod
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+!ec
+
+
+
+!bc pycod
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+!ec
+
+
+
+
+
+!split
+===== Boosting, a Bird's Eye View =====
+
+The basic idea is to combine weak classifiers in order to create a good
+classifier. With a weak classifier we often intend a classifier which
+produces results which are only slightly better than we would get by
+random guesses.
+
+This is done by applying in an iterative way a weak (or a standard
+classifier like decision trees) to modify the data. In each iteration
+we emphasize those observations which are misclassified by weighting
+them with a factor.
+
+
+!split
+===== What is boosting? Additive Modelling/Iterative Fitting =====
+
+Boosting is a way of fitting an additive expansion in a set of
+elementary basis functions like for example some simple polynomials.
+Assume for example that we have a function
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+
+where $\beta_m$ are the expansion parameters to be determined in a
+minimization process and $b(x;\gamma_m)$ are some simple functions of
+the multivariable parameter $x$ which is characterized by the
+parameters $\gamma_m$.
+
+As an example, consider the Sigmoid function we used in logistic
+regression. In that case, we can translate the function
+$b(x;\gamma_m)$ into the Sigmoid function
+
+
+!bt
+\[
+\sigma(t) = \frac{1}{1+\exp{(-t)}},
+\]
+!et
+
+where $t=\gamma_0+\gamma_1 x$ and the parameters $\gamma_0$ and
+$\gamma_1$ were determined by the Logistic Regression fitting
+algorithm.
+
+As another example, consider the cost function we defined for linear regression
+!bt
+\[
+C(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+In this case the function $f(x)$ was replaced by the design matrix
+$\bm{X}$ and the unknown linear regression parameters $\bm{\beta}$,
+that is $\bm{f}=\bm{X}\bm{\beta}$. In linear regression we can
+simply invert a matrix and obtain the parameters $\beta$ by
+
+!bt
+\[
+\bm{\beta}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+
+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$.
+
+
+!split
+===== Iterative Fitting, Regression and Squared-error Cost Function =====
+
+The way we proceed is as follows (here we specialize to the squared-error cost function)
+
+o Establish a cost function, here ${\cal C}(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m)$.
+o Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.
+o For $m=1:M$
+ o minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$
+ o This gives the optimal values $\beta_m$ and $\gamma_m$
+ o Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$
+
+We could use any of the algorithms we have discussed till now. If we
+use trees, $\gamma$ parameterizes the split variables and split points
+at the internal nodes, and the predictions at the terminal nodes.
+
+
+!split
+===== Squared-Error Example and Iterative Fitting =====
+
+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+
+For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$.
+
+This means that for every iteration $m$, we need to optimize
+
+!bt
+\[
+(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
+\]
+!et
+
+We start our iteration by simply setting $f_0(x)=0$.
+Taking the derivatives with respect to $\beta$ and $\gamma$ we obtain
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
+\]
+!et
+We can then rewrite these equations as (defining $\bm{w}=\bm{e}+\gamma \bm{x})$ with $\bm{e}$ being the unit vector)
+!bt
+\[
+\gamma \bm{w}^T(\bm{y}-\beta\gamma \bm{w})=0,
+\]
+!et
+which gives us $\beta = \bm{w}^T\bm{y}/(\bm{w}^T\bm{w})$. Similarly we have
+!bt
+\[
+\beta\gamma \bm{x}^T(\bm{y}-\beta(1+\gamma \bm{x}))=0,
+\]
+!et
+
+which leads to $\gamma =(\bm{x}^T\bm{y}-\beta\bm{x}^T\bm{e})/(\beta\bm{x}^T\bm{x})$. Inserting
+for $\beta$ gives us an equation for $\gamma$. This is a non-linear equation in the unknown $\gamma$ and has to be solved numerically.
+
+The solution to these two equations gives us in turn $\beta_1$ and $\gamma_1$ leading to the new expression for $f_1(x)$ as
+$f_1(x) = \beta_1(1+\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$.
+
+
+
+!split
+===== Iterative Fitting, Classification and AdaBoost =====
+
+Let us consider a binary classification problem with two outcomes $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values
+$\{-1,1\}$.
+
+The error rate of the training sample is then
+
+!bt
+\[
+\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
+\]
+!et
+
+The iterative procedure starts with defining a weak classifier whose
+error rate is barely better than random guessing. The iterative
+procedure in boosting is to sequentially apply a weak
+classification algorithm to repeatedly modified versions of the data
+producing a sequence of weak classifiers $G_m(x)$.
+
+Here we will express our function $f(x)$ in terms of $G(x)$. That is
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+will be a function of
+!bt
+\[
+G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
+\]
+!et
+
+
+
+!split
+===== Adaptive Boosting, AdaBoost =====
+
+In our iterative procedure we define thus
+!bt
+\[
+f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
+\]
+!et
+
+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
+exponential cost/loss function defined as
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
+\]
+!et
+
+We optimize $\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.
+This is normally done in two steps. Let us however first rewrite the cost function as
+
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
+\]
+!et
+where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$.
+
+!split
+===== Building up AdaBoost =====
+
+First, for any $\beta > 0$, we optimize $G$ by setting
+!bt
+\[
+G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
+\]
+!et
+which is the classifier that minimizes the weighted error rate in predicting $y$.
+
+We can do this by rewriting
+!bt
+\[
+\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
+\]
+!et
+which can be rewritten as
+!bt
+\[
+(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
+\]
+!et
+which leads to
+!bt
+\[
+\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
+\]
+!et
+where we have redefined the error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
+\]
+!et
+which leads to an update of
+!bt
+\[
+f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
+\]
+!et
+This leads to the new weights
+!bt
+\[
+w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
+\]
+!et
+
+
+!split
+===== Adaptive boosting: AdaBoost, Basic Algorithm =====
+
+The algorithm here is rather straightforward. Assume that our weak
+classifier is a decision tree and we consider a binary set of outputs
+with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. Our design matrix is given in terms of the
+feature/predictor vectors
+$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}]$. Finally, we define also a
+classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$.
+
+We have already defined the misclassification error $\mathrm{err}$ as
+!bt
+\[
+\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
+\]
+!et
+where the function $I()$ is one if we misclassify and zero if we classify correctly.
+
+!split
+===== Basic Steps of AdaBoost =====
+
+With the above definitions we are now ready to set up the algorithm for AdaBoost.
+The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
+o We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is easy to see that we must have $\sum_{i=0}^{n-1}w_i = 1$.
+o We rewrite the misclassification error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
+\]
+!et
+o Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.
+ o Fit then a given classifier to the training set using the weights $w_i$.
+ o Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.
+ o Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$
+ o Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$.
+o Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$.
+
+For the iterations with $m \le 2$ the weights are modified
+individually at each steps. The observations which were misclassified
+at iteration $m-1$ have a weight which is larger than those which were
+classified properly. As this proceeds, the observations which were
+difficult to classifiy correctly are given a larger influence. Each
+new classification step $m$ is then forced to concentrate on those
+observations that are missed in the previous iterations.
+
+
+
+!split
+===== AdaBoost Examples =====
+
+Using _Scikit-Learn_ it is easy to apply the adaptive boosting algorithm, as done here.
+
+!bc pycod
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+!ec
+
+
+!split
+===== AdaBoost for Regression =====
+
+Here we present "Drucker's AdaBoost":"https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf" tailored for regression.
+
+In bagging, each training example is equally likely to be
+picked. In boosting, the probability of a particular
+example being in the training set of a particular machine
+depends on the performance of the prior machines on
+that example. The following is a modification of
+Adaboost by Drucker.
+
+Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\dots,n$. As we have done earlier, we could pick say $80\%$ of the data set for training. The algorithm runs as follows:
+o We define the probability that the training sample $i$ is in the set by $p_i = w_i/\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\sum_iw_i]$.
+o We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
+o Using every member of the training set with the chosen regression machine we obtain then a prediction $\tilde{y}_i$.
+o We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value
+$L_i\in [0,1]$.
+
+!split
+===== Gradient boosting: Basics with Steepest Descent =====
+
+Gradient boosting is again a similar technique to Adaptive boosting,
+it combines so-called weak classifiers or regressors into a strong
+method via a series of iterations.
+
+In order to understand the method, let us illustrate its basics by
+bringing back the essential steps in linear regression, where our cost
+function was the least squares function.
+
+!split
+===== The Squared-Error again! Steepest Descent =====
+
+We start again with our cost function ${\cal C}(\bm{y}m\bm{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i))$ where we want to minimize
+This means that for every iteration, we need to optimize
+
+!bt
+\[
+(\hat{\bm{f}}) = \mathrm{argmin}_{\bm{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as
+!bt
+\[
+f_M(x) = \sum_{m=0}^M h_m(x).
+\]
+!et
+
+In the steepest decent approach we approximate $h_m(x) = -\rho_m g_m(x)$, where $\rho_m$ is a scalar and $g_m(x)$ the gradient defined as
+!bt
+\[
+g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
+\]
+!et
+
+With the new gradient we can update $f_m(x) = f_{m-1}(x) -\rho_m g_m(x)$. Using the above squared-error function we see that
+the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.
+
+Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have
+!bt
+\[
+(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
+\]
+!et
+
+!split
+===== Steepest Descent Example =====
+
+Optimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that
+!bt
+\[
+f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
+\]
+!et
+We can then proceed and compute
+!bt
+\[
+g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,
+\]
+!et
+and find a new value for $\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called _gradient boosting_.
+
+!split
+===== Gradient Boosting, algorithm =====
+
+Suppose we have a cost function $C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function
+!bt
+\[
+C(\bm{y},\bm{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+The way we proceed in an iterative fashion is to
+o Initialize our estimate $f_0(x)$.
+o For $m=1:M$, we
+ o compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x)$;
+ o fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;
+ o update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$;
+o The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$.
+
+!split
+===== Gradient Boosting Example, Regression =====
+
+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above.
+
+
+!split
+===== Gradient Boosting, Examples of Regression =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+ model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+!ec
+
+
+!split
+===== Gradient Boosting, Classification Example =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+!ec
+
+
+!split
+===== XGBoost: Extreme Gradient Boosting =====
+
+
+"XGBoost":"https://github.com/dmlc/xgboost" or Extreme Gradient
+Boosting, is an optimized distributed gradient boosting library
+designed to be highly efficient, flexible and portable. It implements
+machine learning algorithms under the Gradient Boosting
+framework. XGBoost provides a parallel tree boosting that solve many
+data science problems in a fast and accurate way. See the "article by Chen and Guestrin":"https://arxiv.org/abs/1603.02754".
+
+The authors design and build a highly scalable end-to-end tree
+boosting system. It has a theoretically justified weighted quantile
+sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.
+
+It is now the algorithm which wins essentially all ML competitions!!!
+
+!split
+===== Regression Case =====
+
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+ model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+!ec
+
+!split
+===== Xgboost on the Cancer Data =====
+
+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+!ec
diff --git a/doc/src/week46/week46.do.txt b/doc/src/week46/week46.do.txt
new file mode 100644
index 000000000..f0638e0d3
--- /dev/null
+++ b/doc/src/week46/week46.do.txt
@@ -0,0 +1,1143 @@
+TITLE: Week 46: Support Vector Machines
+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
+
+!split
+===== Support Vector Machines, overarching aims =====
+
+A Support Vector Machine (SVM) is a very powerful and versatile
+Machine Learning method, capable of performing linear or nonlinear
+classification, regression, and even outlier detection. It is one of
+the most popular models in Machine Learning, and anyone interested in
+Machine Learning should have it in their toolbox. SVMs are
+particularly well suited for classification of complex but small-sized or
+medium-sized datasets.
+
+The case with two well-separated classes only can be understood in an
+intuitive way in terms of lines in a two-dimensional space separating
+the two classes (see figure below).
+
+The basic mathematics behind the SVM is however less familiar to most of us.
+It relies on the definition of hyperplanes and the
+definition of a _margin_ which separates classes (in case of
+classification problems) of variables. It is also used for regression
+problems.
+
+With SVMs we distinguish between hard margin and soft margins. The
+latter introduces a so-called softening parameter to be discussed
+below. We distinguish also between linear and non-linear
+approaches. The latter are the most frequent ones since it is rather
+unlikely that we can separate classes easily by say straight lines.
+
+!split
+===== Hyperplanes and all that =====
+
+The theory behind support vector machines (SVM hereafter) is based on
+the mathematical description of so-called hyperplanes. Let us start
+with a two-dimensional case. This will also allow us to introduce our
+first SVM examples. These will be tailored to the case of two specific
+classes, as displayed in the figure here based on the usage of the petal data.
+
+We assume here that our data set can be well separated into two
+domains, where a straight line does the job in the separating the two
+classes. Here the two classes are represented by either squares or
+circles.
+!bc pycod
+from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)] # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+ max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC: ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+
+
+!ec
+
+
+
+
+!split
+===== What is a hyperplane? =====
+
+The aim of the SVM algorithm is to find a hyperplane in a
+$p$-dimensional space, where $p$ is the number of features that
+distinctly classifies the data points.
+
+In a $p$-dimensional space, a hyperplane is what we call an affine subspace of dimension of $p-1$.
+As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is
+a two-dimensional subspace, or stated simply, a plane.
+
+In two dimensions, with the variables $x_1$ and $x_2$, the hyperplane is defined as
+!bt
+\[
+b+w_1x_1+w_2x_2=0,
+\]
+!et
+
+where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line
+$b+w_1x_1+w_2x_2=0$.
+In two dimensions we define the vectors $\bm{x} =[x1,x2]$ and $\bm{w}=[w1,w2]$.
+We can then rewrite the above equation as
+
+!bt
+\[
+\bm{x}^T\bm{w}+b=0.
+\]
+!et
+
+!split
+===== A $p$-dimensional space of features =====
+
+We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \pm 1$.
+In a $p$-dimensional space of say $p$ features we have a hyperplane defines as
+!bt
+\[
+b+wx_1+w_2x_2+\dots +w_px_p=0.
+\]
+!et
+If we define a
+matrix $\bm{X}=\left[\bm{x}_1,\bm{x}_2,\dots, \bm{x}_p\right]$
+of dimension $n\times p$, where $n$ represents the observations for each feature and each vector $x_i$ is a column vector of the matrix $\bm{X}$,
+!bt
+\[
+\bm{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}.
+\]
+!et
+If the above condition is not met for a given vector $\bm{x}_i$ we have
+!bt
+\[
+b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0,
+\]
+!et
+if our output $y_i=1$.
+In this case we say that $\bm{x}_i$ lies on one of the sides of the hyperplane and if
+!bt
+\[
+b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0,
+\]
+!et
+for the class of observations $y_i=-1$,
+then $\bm{x}_i$ lies on the other side.
+
+Equivalently, for the two classes of observations we have
+!bt
+\[
+y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0.
+\]
+!et
+
+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.
+
+!split
+===== The two-dimensional case =====
+
+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional
+plane. To separate the two classes of data points, there are many
+possible lines (hyperplanes if you prefer a more strict naming)
+that could be chosen. Our objective is to find a
+plane that has the maximum margin, i.e the maximum distance between
+data points of both classes. Maximizing the margin distance provides
+some reinforcement so that future data points can be classified with
+more confidence.
+
+What a linear classifier attempts to accomplish is to split the
+feature space into two half spaces by placing a hyperplane between the
+data points. This hyperplane will be our decision boundary. All
+points on one side of the plane will belong to class one and all points
+on the other side of the plane will belong to the second class two.
+
+Unfortunately there are many ways in which we can place a hyperplane
+to divide the data. Below is an example of two candidate hyperplanes
+for our data sample.
+
+!split
+===== Getting into the details =====
+
+Let us define the function
+!bt
+\[
+f(x) = \bm{w}^T\bm{x}+b = 0,
+\]
+!et
+as the function that determines the line $L$ that separates two classes (our two features), see the figure here.
+
+
+Any point defined by $\bm{x}_i$ and $\bm{x}_2$ on the line $L$ will satisfy $\bm{w}^T(\bm{x}_1-\bm{x}_2)=0$.
+
+The signed distance $\delta$ from any point defined by a vector $\bm{x}$ and a point $\bm{x}_0$ on the line $L$ is then
+!bt
+\[
+\delta = \frac{1}{\vert\vert \bm{w}\vert\vert}(\bm{w}^T\bm{x}+b).
+\]
+!et
+
+!split
+===== First attempt at a minimization approach =====
+
+How do we find the parameter $b$ and the vector $\bm{w}$? What we could
+do is to define a cost function which now contains the set of all
+misclassified points $M$ and attempt to minimize this function
+
+!bt
+\[
+C(\bm{w},b) = -\sum_{i\in M} y_i(\bm{w}^T\bm{x}_i+b).
+\]
+!et
+
+We could now for example define all values $y_i =1$ as misclassified in case we have $\bm{w}^T\bm{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us
+!bt
+\[
+\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial C}{\partial \bm{w}} = -\sum_{i\in M} y_ix_i.
+\]
+!et
+
+!split
+===== Solving the equations =====
+
+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations
+!bt
+\[
+b \leftarrow b +\eta \frac{\partial C}{\partial b},
+\]
+!et
+and
+!bt
+\[
+\bm{w} \leftarrow \bm{w} +\eta \frac{\partial C}{\partial \bm{w}},
+\]
+!et
+where $\eta$ is our by now well-known learning rate.
+
+
+!split
+===== Code Example =====
+
+The equations we discussed above can be coded rather easily (the
+framework is similar to what we developed for logistic
+regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way.
+!bc pycod
+
+!ec
+
+!split
+===== Problems with the Simpler Approach =====
+
+
+There are however problems with this approach, although it looks
+pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes.
+
+
+For small
+gaps between the entries, we may also end up needing many iterations
+before the solutions converge and if the data cannot be separated
+properly into two distinct classes, we may not experience a converge
+at all.
+
+!split
+===== A better approach =====
+
+A better approach is rather to try to define a large margin between
+the two classes (if they are well separated from the beginning).
+
+Thus, we wish to find a margin $M$ with $\bm{w}$ normalized to
+$\vert\vert \bm{w}\vert\vert =1$ subject to the condition
+
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p.
+\]
+!et
+All points are thus at a signed distance from the decision boundary defined by the line $L$. The parameters $b$ and $w_1$ and $w_2$ define this line.
+
+We seek thus the largest value $M$ defined by
+!bt
+\[
+\frac{1}{\vert \vert \bm{w}\vert\vert}y_i(\bm{w}^T\bm{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n,
+\]
+!et
+or just
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq M\vert \vert \bm{w}\vert\vert \hspace{0.1cm}\forall i.
+\]
+!et
+If we scale the equation so that $\vert \vert \bm{w}\vert\vert = 1/M$, we have to find the minimum of
+$\bm{w}^T\bm{w}=\vert \vert \bm{w}\vert\vert$ (the norm) subject to the condition
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq 1 \hspace{0.1cm}\forall i.
+\]
+!et
+
+We have thus defined our margin as the invers of the norm of
+$\bm{w}$. We want to minimize the norm in order to have a as large as
+possible margin $M$. Before we proceed, we need to remind ourselves
+about Lagrangian multipliers.
+
+!split
+===== A quick Reminder on Lagrangian Multipliers =====
+
+Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an
+extreme we have
+!bt
+\[
+df=0.
+\]
+!et
+A necessary and sufficient condition is
+!bt
+\[
+\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
+\]
+!et
+due to
+!bt
+\[
+df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz.
+\]
+!et
+In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)
+so that they are no longer all independent. It is possible at least in principle to use each
+constraint to eliminate one variable
+and to proceed with a new and smaller set of independent varables.
+
+The use of so-called Lagrangian multipliers is an alternative technique when the elimination
+of variables is incovenient or undesirable. Assume that we have an equation of constraint on
+the variables $x,y,z$
+!bt
+\[
+\phi(x,y,z) = 0,
+\]
+!et
+ resulting in
+!bt
+\[
+d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0.
+\]
+!et
+Now we cannot set anymore
+!bt
+\[
+\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
+\]
+!et
+if $df=0$ is wanted
+because there are now only two independent variables! Assume $x$ and $y$ are the independent
+variables.
+Then $dz$ is no longer arbitrary.
+
+!split
+===== Adding the Multiplier =====
+
+However, we can add to
+!bt
+\[
+df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz,
+\]
+!et
+a multiplum of $d\phi$, viz. $\lambda d\phi$, resulting in
+!bt
+\[
+df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda
+\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+
+(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0.
+\]
+!et
+Our multiplier is chosen so that
+!bt
+\[
+\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0.
+\]
+!et
+
+We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have
+!bt
+\[
+\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0.
+\]
+!et
+When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and
+$\lambda$. Actually we want only $x,y,z$, $\lambda$ needs not to be determined,
+it is therefore often called
+Lagrange's undetermined multiplier.
+If we have a set of constraints $\phi_k$ we have the equations
+!bt
+\[
+\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0.
+\]
+!et
+
+!split
+===== Setting up the Problem =====
+In order to solve the above problem, we define the following Lagrangian function to be minimized
+!bt
+\[
+{\cal L}(\lambda,b,\bm{w})=\frac{1}{2}\bm{w}^T\bm{w}-\sum_{i=1}^n\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b)-1\right],
+\]
+!et
+where $\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\lambda_i \geq 0$.
+
+Taking the derivatives with respect to $b$ and $\bm{w}$ we obtain
+!bt
+\[
+\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal L}}{\partial \bm{w}} = 0 = \bm{w}-\sum_{i} \lambda_iy_i\bm{x}_i.
+\]
+!et
+Inserting these constraints into the equation for ${\cal L}$ we obtain
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$ and $\sum_i\lambda_iy_i=0$.
+We must in addition satisfy the "Karush-Kuhn-Tucker":"https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions" (KKT) condition
+!bt
+\[
+\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b) -1\right] \hspace{0.1cm}\forall i.
+\]
+!et
+o If $\lambda_i > 0$, then $y_i(\bm{w}^T\bm{x}_i+b)=1$ and we say that $x_i$ is on the boundary.
+o If $y_i(\bm{w}^T\bm{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\lambda_i=0$.
+When $\lambda_i > 0$, the vectors $\bm{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$.
+
+!split
+===== The problem to solve =====
+
+We can rewrite
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\lambda$ the following problem
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1\bm{x}_1^T\bm{x}_1 & y_1y_2\bm{x}_1^T\bm{x}_2 & \dots & \dots & y_1y_n\bm{x}_1^T\bm{x}_n \\
+y_2y_1\bm{x}_2^T\bm{x}_1 & y_2y_2\bm{x}_2^T\bm{x}_2 & \dots & \dots & y_1y_n\bm{x}_2^T\bm{x}_n \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1\bm{x}_n^T\bm{x}_1 & y_ny_2\bm{x}_n^T\bm{x}_2 & \dots & \dots & y_ny_n\bm{x}_n^T\bm{x}_n \\
+\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+
+
+!split
+===== The last steps =====
+
+Solving the above problem, yields the values of $\lambda_i$.
+To find the coefficients of your hyperplane we need simply to compute
+!bt
+\[
+\bm{w}=\sum_{i} \lambda_iy_i\bm{x}_i.
+\]
+!et
+With our vector $\bm{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1,
+\]
+!et
+resulting in
+!bt
+\[
+b = \frac{1}{y_i}-\bm{w}^T\bm{x}_i,
+\]
+!et
+or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have
+!bt
+\[
+b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\bm{x}_i^T\bm{x}_j\right).
+\]
+!et
+With our hyperplane coefficients we can use our classifier to assign any observation by simply using
+!bt
+\[
+y_i = \mathrm{sign}(\bm{w}^T\bm{x}_i+b).
+\]
+!et
+Below we discuss how to find the optimal values of $\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier.
+
+!split
+===== A soft classifier =====
+
+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.
+
+Suppose now that classes overlap in feature space, as shown in the
+figure here. One way to deal with this problem before we define the
+so-called _kernel approach_, is to allow a kind of slack in the sense
+that we allow some points to be on the wrong side of the margin.
+
+We introduce thus the so-called _slack_ variables $\bm{\xi} =[\xi_1,x_2,\dots,x_n]$ and
+modify our previous equation
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1,
+\]
+!et
+to
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1-\xi_i,
+\]
+!et
+with the requirement $\xi_i\geq 0$. The total violation is now $\sum_i\xi$.
+The value $\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction
+$y_i(\bm{w}^T\bm{x}_i+b)=1$ is on the wrong side of its margin. Hence by bounding the sum $\sum_i \xi_i$,
+we bound the total amount by which predictions fall on the wrong side of their margins.
+
+Misclassifications occur when $\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of
+misclassifications.
+
+!split
+===== Soft optmization problem =====
+
+
+This has in turn the consequences that we change our optmization problem to finding the minimum of
+!bt
+\[
+{\cal L}=\frac{1}{2}\bm{w}^T\bm{w}-\sum_{i=1}^n\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i,
+\]
+!et
+subject to
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i,
+\]
+!et
+with the requirement $\xi_i\geq 0$.
+
+Taking the derivatives with respect to $b$ and $\bm{w}$ we obtain
+!bt
+\[
+\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal L}}{\partial \bm{w}} = 0 = \bm{w}-\sum_{i} \lambda_iy_i\bm{x}_i,
+\]
+!et
+and
+!bt
+\[
+\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i.
+\]
+!et
+Inserting these constraints into the equation for ${\cal L}$ we obtain the same equation as before
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+but now subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ and $0\leq\lambda_i \leq C$.
+We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads
+!bt
+\[
+\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i,
+\]
+!et
+!bt
+\[
+\gamma_i\xi_i = 0,
+\]
+!et
+and
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i.
+\]
+!et
+
+!split
+===== Kernels and non-linearity =====
+
+The cases we have studied till now, were all characterized by two classes
+with a close to linear separability. The classifiers we have described
+so far find linear boundaries in our input feature space. It is
+possible to make our procedure more flexible by exploring the feature
+space using other basis expansions such as higher-order polynomials,
+wavelets, splines etc.
+
+If our feature space is not easy to separate, as shown in the figure
+here, we can achieve a better separation by introducing more complex
+basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to
+obtain a separation between the classes which is almost linear.
+
+The change of basis, from $x\rightarrow z=\phi(x)$ leads to the same type of equations to be solved, except that
+we need to introduce for example a polynomial transformation to a two-dimensional training set.
+
+!bc pycod
+import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+!ec
+
+
+
+!split
+===== The equations =====
+
+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with $x_i$ and $y_i$ as variables)
+!bt
+\[
+z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right).
+\]
+!et
+
+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors
+!bt
+\[
+y_i(\bm{w}^T\bm{z}_i+b)= 1 \hspace{0.1cm}\forall i,
+\]
+!et
+from which we also find $b$.
+To compute $\bm{z}_i^T\bm{z}_j$ we define the kernel $K(\bm{x}_i,\bm{x}_j)$ as
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=\bm{z}_i^T\bm{z}_j= \phi(\bm{x}_i)^T\phi(\bm{x}_j).
+\]
+!et
+For the above example, the kernel reads
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.
+\]
+!et
+
+We note that this is nothing but the dot product of the two original
+vectors $(\bm{x}_i^T\bm{x}_j)^2$. Instead of thus computing the
+product in the Lagrangian of $\bm{z}_i^T\bm{z}_j$ we simply compute
+the dot product $(\bm{x}_i^T\bm{x}_j)^2$.
+
+
+This leads to the so-called
+kernel trick and the result leads to the same as if we went through
+the trouble of performing the transformation
+$\phi(\bm{x}_i)^T\phi(\bm{x}_j)$ during the SVM calculations.
+
+
+!split
+===== The problem to solve =====
+Using our definition of the kernel We can rewrite again the Lagrangian
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{z}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
+y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
+\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+If we add the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
+
+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type
+!bt
+\begin{align*}
+ &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \hspace{0.2cm} \wedge \bm{A}\bm{\lambda}=f.
+\end{align*}
+!et
+Below we discuss how to solve these equations. Here we note that the matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$.
+Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. How to set up the matrix $\bm{G}$ is discussed later. Here note that the inequalities $0\leq \lambda_i \leq C$ can be split up into
+$0\leq \lambda_i$ and $\lambda_i \leq C$. These two inequalities define then the matrix $\bm{G}$ and the vector $\bm{h}$.
+
+
+!split
+===== Different kernels and Mercer's theorem =====
+
+There are several popular kernels being used. These are
+o Linear: $K(\bm{x},\bm{y})=\bm{x}^T\bm{y}$,
+o Polynomial: $K(\bm{x},\bm{y})=(\bm{x}^T\bm{y}+\gamma)^d$,
+o Gaussian Radial Basis Function: $K(\bm{x},\bm{y})=\exp{\left(-\gamma\vert\vert\bm{x}-\bm{y}\vert\vert^2\right)}$,
+o Tanh: $K(\bm{x},\bm{y})=\tanh{(\bm{x}^T\bm{y}+\gamma)}$,
+and many other ones.
+
+An important theorem for us is "Mercer's
+theorem":"https://en.wikipedia.org/wiki/Mercer%27s_theorem". The
+theorem states that if a kernel function $K$ is symmetric, continuous
+and leads to a positive semi-definite matrix $\bm{P}$ then there
+exists a function $\phi$ that maps $\bm{x}_i$ and $\bm{x}_j$ into
+another space (possibly with much higher dimensions) such that
+
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=\phi(\bm{x}_i)^T\phi(\bm{x}_j).
+\]
+!et
+
+So you can use $K$ as a kernel since you know $\phi$ exists, even if
+you don’t know what $\phi$ is.
+
+Note that some frequently used kernels (such as the Sigmoid kernel)
+don’t respect all of Mercer’s conditions, yet they generally work well
+in practice.
+
+
+!split
+===== The moons example =====
+!bc pycod
+from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+ plt.axis(axes)
+ plt.grid(True, which='both')
+ plt.xlabel(r"$x_1$", fontsize=20)
+ plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+ ("poly_features", PolynomialFeatures(degree=3)),
+ ("scaler", StandardScaler()),
+ ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+ ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+ x0s = np.linspace(axes[0], axes[1], 100)
+ x1s = np.linspace(axes[2], axes[3], 100)
+ x0, x1 = np.meshgrid(x0s, x1s)
+ X = np.c_[x0.ravel(), x1.ravel()]
+ y_pred = clf.predict(X).reshape(x0.shape)
+ y_decision = clf.decision_function(X).reshape(x0.shape)
+ plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+ plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+ ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+ ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+ return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+ xy=(X1D[3, 0], 0),
+ xytext=(-0.5, 0.20),
+ ha="center",
+ arrowprops=dict(facecolor='black', shrink=0.1),
+ fontsize=18,
+ )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$ ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+ xy=(XK[3, 0], XK[3, 1]),
+ xytext=(0.65, 0.50),
+ ha="center",
+ arrowprops=dict(facecolor='black', shrink=0.1),
+ fontsize=18,
+ )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+ k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+ print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+ ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+ rbf_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+ ])
+ rbf_kernel_svm_clf.fit(X, y)
+ svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+ plt.subplot(221 + i)
+ plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+ plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+ gamma, C = hyperparams[i]
+ plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+!ec
+
+
+
+!split
+===== Mathematical optimization of convex functions =====
+
+A mathematical (quadratic) optimization problem, or just optimization problem, has the form
+!bt
+\begin{align*}
+ &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f.
+\end{align*}
+!et
+subject to some constraints for say a selected set $i=1,2,\dots, n$.
+In our case we are optimizing with respect to the Lagrangian multipliers $\lambda_i$, and the
+vector $\bm{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n]$ is the optimization variable we are dealing with.
+
+In our case we are particularly interested in a class of optimization problems called convex optmization problems.
+In our discussion on gradient descent methods we discussed at length the definition of a convex function.
+
+Convex optimization problems play a central role in applied mathematics and we recommend strongly "Boyd and Vandenberghe's text on the topics":"http://web.stanford.edu/~boyd/cvxbook/".
+
+
+
+!split
+===== How do we solve these problems? =====
+
+If we use Python as programming language and wish to venture beyond
+_scikit-learn_, _tensorflow_ and similar software which makes our
+lives so much easier, we need to dive into the wonderful world of
+quadratic programming. We can, if we wish, solve the minimization
+problem using say standard gradient methods or conjugate gradient
+methods. However, these methods tend to exhibit a rather slow
+converge. So, welcome to the promised land of quadratic programming.
+
+The functions we need are contained in the quadratic programming package _CVXOPT_ and we need to import it together with _numpy_ as
+
+!bc pycod
+import numpy
+import cvxopt
+!ec
+
+This will make our life much easier. You don't need t write your own optimizer.
+
+
+!split
+===== A simple example =====
+
+We remind ourselves about the general problem we want to solve
+!bt
+\begin{align*}
+ &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\bm{x}^T\bm{P}\bm{x}+\bm{q}^T\bm{x},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \bm{G}\bm{x} \preceq \bm{h} \wedge \bm{A}\bm{x}=f.
+\end{align*}
+!et
+
+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem
+!bt
+\begin{align*}
+ &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber
+ &\mathrm{subject to} \\ \nonumber
+ &x, y \geq 0 \\ \nonumber
+ &x+3y \geq 15 \\ \nonumber
+ &2x+5y \leq 100 \\ \nonumber
+ &3x+4y \leq 80. \\ \nonumber
+\end{align*}
+!et
+The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)
+!bt
+\[
+\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}.
+\]
+!et
+Similarly, we can now set up the inequalities (we need to change $\geq$ to $\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation
+!bt
+\[
+\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
+\]
+!et
+We have collapsed all the inequalities into a single matrix $\bm{G}$. We see also that our matrix
+!bt
+\[
+\bm{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix}
+\]
+!et
+is clearly positive semi-definite (all eigenvalues larger or equal zero).
+Finally, the vector $\bm{h}$ is defined as
+!bt
+\[
+\bm{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
+\]
+!et
+
+
+Since we don't have any equalities the matrix $\bm{A}$ is set to zero
+The following code solves the equations for us
+!bc pycod
+# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’]
+sol[’primal objective’]
+!ec
+
+!split
+===== Back to the more realistic cases =====
+
+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the _slack_ parameter $C$ we have
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
+y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2K(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
+\end{bmatrix}\bm{\lambda}-\mathbb{I}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
+
+_code will be added_
+
+
diff --git a/doc/src/week47/week47.do.txt b/doc/src/week47/week47.do.txt
new file mode 100644
index 000000000..26c8aa497
--- /dev/null
+++ b/doc/src/week47/week47.do.txt
@@ -0,0 +1,1143 @@
+TITLE: Week 47: Support Vector Machines
+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
+
+!split
+===== Support Vector Machines, overarching aims =====
+
+A Support Vector Machine (SVM) is a very powerful and versatile
+Machine Learning method, capable of performing linear or nonlinear
+classification, regression, and even outlier detection. It is one of
+the most popular models in Machine Learning, and anyone interested in
+Machine Learning should have it in their toolbox. SVMs are
+particularly well suited for classification of complex but small-sized or
+medium-sized datasets.
+
+The case with two well-separated classes only can be understood in an
+intuitive way in terms of lines in a two-dimensional space separating
+the two classes (see figure below).
+
+The basic mathematics behind the SVM is however less familiar to most of us.
+It relies on the definition of hyperplanes and the
+definition of a _margin_ which separates classes (in case of
+classification problems) of variables. It is also used for regression
+problems.
+
+With SVMs we distinguish between hard margin and soft margins. The
+latter introduces a so-called softening parameter to be discussed
+below. We distinguish also between linear and non-linear
+approaches. The latter are the most frequent ones since it is rather
+unlikely that we can separate classes easily by say straight lines.
+
+!split
+===== Hyperplanes and all that =====
+
+The theory behind support vector machines (SVM hereafter) is based on
+the mathematical description of so-called hyperplanes. Let us start
+with a two-dimensional case. This will also allow us to introduce our
+first SVM examples. These will be tailored to the case of two specific
+classes, as displayed in the figure here based on the usage of the petal data.
+
+We assume here that our data set can be well separated into two
+domains, where a straight line does the job in the separating the two
+classes. Here the two classes are represented by either squares or
+circles.
+!bc pycod
+from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)] # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+ max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC: ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+
+
+!ec
+
+
+
+
+!split
+===== What is a hyperplane? =====
+
+The aim of the SVM algorithm is to find a hyperplane in a
+$p$-dimensional space, where $p$ is the number of features that
+distinctly classifies the data points.
+
+In a $p$-dimensional space, a hyperplane is what we call an affine subspace of dimension of $p-1$.
+As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is
+a two-dimensional subspace, or stated simply, a plane.
+
+In two dimensions, with the variables $x_1$ and $x_2$, the hyperplane is defined as
+!bt
+\[
+b+w_1x_1+w_2x_2=0,
+\]
+!et
+
+where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line
+$b+w_1x_1+w_2x_2=0$.
+In two dimensions we define the vectors $\bm{x} =[x1,x2]$ and $\bm{w}=[w1,w2]$.
+We can then rewrite the above equation as
+
+!bt
+\[
+\bm{x}^T\bm{w}+b=0.
+\]
+!et
+
+!split
+===== A $p$-dimensional space of features =====
+
+We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \pm 1$.
+In a $p$-dimensional space of say $p$ features we have a hyperplane defines as
+!bt
+\[
+b+wx_1+w_2x_2+\dots +w_px_p=0.
+\]
+!et
+If we define a
+matrix $\bm{X}=\left[\bm{x}_1,\bm{x}_2,\dots, \bm{x}_p\right]$
+of dimension $n\times p$, where $n$ represents the observations for each feature and each vector $x_i$ is a column vector of the matrix $\bm{X}$,
+!bt
+\[
+\bm{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}.
+\]
+!et
+If the above condition is not met for a given vector $\bm{x}_i$ we have
+!bt
+\[
+b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0,
+\]
+!et
+if our output $y_i=1$.
+In this case we say that $\bm{x}_i$ lies on one of the sides of the hyperplane and if
+!bt
+\[
+b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0,
+\]
+!et
+for the class of observations $y_i=-1$,
+then $\bm{x}_i$ lies on the other side.
+
+Equivalently, for the two classes of observations we have
+!bt
+\[
+y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0.
+\]
+!et
+
+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.
+
+!split
+===== The two-dimensional case =====
+
+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional
+plane. To separate the two classes of data points, there are many
+possible lines (hyperplanes if you prefer a more strict naming)
+that could be chosen. Our objective is to find a
+plane that has the maximum margin, i.e the maximum distance between
+data points of both classes. Maximizing the margin distance provides
+some reinforcement so that future data points can be classified with
+more confidence.
+
+What a linear classifier attempts to accomplish is to split the
+feature space into two half spaces by placing a hyperplane between the
+data points. This hyperplane will be our decision boundary. All
+points on one side of the plane will belong to class one and all points
+on the other side of the plane will belong to the second class two.
+
+Unfortunately there are many ways in which we can place a hyperplane
+to divide the data. Below is an example of two candidate hyperplanes
+for our data sample.
+
+!split
+===== Getting into the details =====
+
+Let us define the function
+!bt
+\[
+f(x) = \bm{w}^T\bm{x}+b = 0,
+\]
+!et
+as the function that determines the line $L$ that separates two classes (our two features), see the figure here.
+
+
+Any point defined by $\bm{x}_i$ and $\bm{x}_2$ on the line $L$ will satisfy $\bm{w}^T(\bm{x}_1-\bm{x}_2)=0$.
+
+The signed distance $\delta$ from any point defined by a vector $\bm{x}$ and a point $\bm{x}_0$ on the line $L$ is then
+!bt
+\[
+\delta = \frac{1}{\vert\vert \bm{w}\vert\vert}(\bm{w}^T\bm{x}+b).
+\]
+!et
+
+!split
+===== First attempt at a minimization approach =====
+
+How do we find the parameter $b$ and the vector $\bm{w}$? What we could
+do is to define a cost function which now contains the set of all
+misclassified points $M$ and attempt to minimize this function
+
+!bt
+\[
+C(\bm{w},b) = -\sum_{i\in M} y_i(\bm{w}^T\bm{x}_i+b).
+\]
+!et
+
+We could now for example define all values $y_i =1$ as misclassified in case we have $\bm{w}^T\bm{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us
+!bt
+\[
+\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial C}{\partial \bm{w}} = -\sum_{i\in M} y_ix_i.
+\]
+!et
+
+!split
+===== Solving the equations =====
+
+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations
+!bt
+\[
+b \leftarrow b +\eta \frac{\partial C}{\partial b},
+\]
+!et
+and
+!bt
+\[
+\bm{w} \leftarrow \bm{w} +\eta \frac{\partial C}{\partial \bm{w}},
+\]
+!et
+where $\eta$ is our by now well-known learning rate.
+
+
+!split
+===== Code Example =====
+
+The equations we discussed above can be coded rather easily (the
+framework is similar to what we developed for logistic
+regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way.
+!bc pycod
+
+!ec
+
+!split
+===== Problems with the Simpler Approach =====
+
+
+There are however problems with this approach, although it looks
+pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes.
+
+
+For small
+gaps between the entries, we may also end up needing many iterations
+before the solutions converge and if the data cannot be separated
+properly into two distinct classes, we may not experience a converge
+at all.
+
+!split
+===== A better approach =====
+
+A better approach is rather to try to define a large margin between
+the two classes (if they are well separated from the beginning).
+
+Thus, we wish to find a margin $M$ with $\bm{w}$ normalized to
+$\vert\vert \bm{w}\vert\vert =1$ subject to the condition
+
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p.
+\]
+!et
+All points are thus at a signed distance from the decision boundary defined by the line $L$. The parameters $b$ and $w_1$ and $w_2$ define this line.
+
+We seek thus the largest value $M$ defined by
+!bt
+\[
+\frac{1}{\vert \vert \bm{w}\vert\vert}y_i(\bm{w}^T\bm{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n,
+\]
+!et
+or just
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq M\vert \vert \bm{w}\vert\vert \hspace{0.1cm}\forall i.
+\]
+!et
+If we scale the equation so that $\vert \vert \bm{w}\vert\vert = 1/M$, we have to find the minimum of
+$\bm{w}^T\bm{w}=\vert \vert \bm{w}\vert\vert$ (the norm) subject to the condition
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) \geq 1 \hspace{0.1cm}\forall i.
+\]
+!et
+
+We have thus defined our margin as the invers of the norm of
+$\bm{w}$. We want to minimize the norm in order to have a as large as
+possible margin $M$. Before we proceed, we need to remind ourselves
+about Lagrangian multipliers.
+
+!split
+===== A quick Reminder on Lagrangian Multipliers =====
+
+Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an
+extreme we have
+!bt
+\[
+df=0.
+\]
+!et
+A necessary and sufficient condition is
+!bt
+\[
+\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
+\]
+!et
+due to
+!bt
+\[
+df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz.
+\]
+!et
+In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)
+so that they are no longer all independent. It is possible at least in principle to use each
+constraint to eliminate one variable
+and to proceed with a new and smaller set of independent varables.
+
+The use of so-called Lagrangian multipliers is an alternative technique when the elimination
+of variables is incovenient or undesirable. Assume that we have an equation of constraint on
+the variables $x,y,z$
+!bt
+\[
+\phi(x,y,z) = 0,
+\]
+!et
+ resulting in
+!bt
+\[
+d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0.
+\]
+!et
+Now we cannot set anymore
+!bt
+\[
+\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
+\]
+!et
+if $df=0$ is wanted
+because there are now only two independent variables! Assume $x$ and $y$ are the independent
+variables.
+Then $dz$ is no longer arbitrary.
+
+!split
+===== Adding the Multiplier =====
+
+However, we can add to
+!bt
+\[
+df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz,
+\]
+!et
+a multiplum of $d\phi$, viz. $\lambda d\phi$, resulting in
+!bt
+\[
+df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda
+\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+
+(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0.
+\]
+!et
+Our multiplier is chosen so that
+!bt
+\[
+\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0.
+\]
+!et
+
+We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have
+!bt
+\[
+\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0.
+\]
+!et
+When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and
+$\lambda$. Actually we want only $x,y,z$, $\lambda$ needs not to be determined,
+it is therefore often called
+Lagrange's undetermined multiplier.
+If we have a set of constraints $\phi_k$ we have the equations
+!bt
+\[
+\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0.
+\]
+!et
+
+!split
+===== Setting up the Problem =====
+In order to solve the above problem, we define the following Lagrangian function to be minimized
+!bt
+\[
+{\cal L}(\lambda,b,\bm{w})=\frac{1}{2}\bm{w}^T\bm{w}-\sum_{i=1}^n\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b)-1\right],
+\]
+!et
+where $\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\lambda_i \geq 0$.
+
+Taking the derivatives with respect to $b$ and $\bm{w}$ we obtain
+!bt
+\[
+\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal L}}{\partial \bm{w}} = 0 = \bm{w}-\sum_{i} \lambda_iy_i\bm{x}_i.
+\]
+!et
+Inserting these constraints into the equation for ${\cal L}$ we obtain
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$ and $\sum_i\lambda_iy_i=0$.
+We must in addition satisfy the "Karush-Kuhn-Tucker":"https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions" (KKT) condition
+!bt
+\[
+\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b) -1\right] \hspace{0.1cm}\forall i.
+\]
+!et
+o If $\lambda_i > 0$, then $y_i(\bm{w}^T\bm{x}_i+b)=1$ and we say that $x_i$ is on the boundary.
+o If $y_i(\bm{w}^T\bm{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\lambda_i=0$.
+When $\lambda_i > 0$, the vectors $\bm{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$.
+
+!split
+===== The problem to solve =====
+
+We can rewrite
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\lambda$ the following problem
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1\bm{x}_1^T\bm{x}_1 & y_1y_2\bm{x}_1^T\bm{x}_2 & \dots & \dots & y_1y_n\bm{x}_1^T\bm{x}_n \\
+y_2y_1\bm{x}_2^T\bm{x}_1 & y_2y_2\bm{x}_2^T\bm{x}_2 & \dots & \dots & y_1y_n\bm{x}_2^T\bm{x}_n \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1\bm{x}_n^T\bm{x}_1 & y_ny_2\bm{x}_n^T\bm{x}_2 & \dots & \dots & y_ny_n\bm{x}_n^T\bm{x}_n \\
+\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+
+
+!split
+===== The last steps =====
+
+Solving the above problem, yields the values of $\lambda_i$.
+To find the coefficients of your hyperplane we need simply to compute
+!bt
+\[
+\bm{w}=\sum_{i} \lambda_iy_i\bm{x}_i.
+\]
+!et
+With our vector $\bm{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1,
+\]
+!et
+resulting in
+!bt
+\[
+b = \frac{1}{y_i}-\bm{w}^T\bm{x}_i,
+\]
+!et
+or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have
+!bt
+\[
+b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\bm{x}_i^T\bm{x}_j\right).
+\]
+!et
+With our hyperplane coefficients we can use our classifier to assign any observation by simply using
+!bt
+\[
+y_i = \mathrm{sign}(\bm{w}^T\bm{x}_i+b).
+\]
+!et
+Below we discuss how to find the optimal values of $\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier.
+
+!split
+===== A soft classifier =====
+
+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.
+
+Suppose now that classes overlap in feature space, as shown in the
+figure here. One way to deal with this problem before we define the
+so-called _kernel approach_, is to allow a kind of slack in the sense
+that we allow some points to be on the wrong side of the margin.
+
+We introduce thus the so-called _slack_ variables $\bm{\xi} =[\xi_1,x_2,\dots,x_n]$ and
+modify our previous equation
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1,
+\]
+!et
+to
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1-\xi_i,
+\]
+!et
+with the requirement $\xi_i\geq 0$. The total violation is now $\sum_i\xi$.
+The value $\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction
+$y_i(\bm{w}^T\bm{x}_i+b)=1$ is on the wrong side of its margin. Hence by bounding the sum $\sum_i \xi_i$,
+we bound the total amount by which predictions fall on the wrong side of their margins.
+
+Misclassifications occur when $\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of
+misclassifications.
+
+!split
+===== Soft optmization problem =====
+
+
+This has in turn the consequences that we change our optmization problem to finding the minimum of
+!bt
+\[
+{\cal L}=\frac{1}{2}\bm{w}^T\bm{w}-\sum_{i=1}^n\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i,
+\]
+!et
+subject to
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i,
+\]
+!et
+with the requirement $\xi_i\geq 0$.
+
+Taking the derivatives with respect to $b$ and $\bm{w}$ we obtain
+!bt
+\[
+\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal L}}{\partial \bm{w}} = 0 = \bm{w}-\sum_{i} \lambda_iy_i\bm{x}_i,
+\]
+!et
+and
+!bt
+\[
+\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i.
+\]
+!et
+Inserting these constraints into the equation for ${\cal L}$ we obtain the same equation as before
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{x}_j,
+\]
+!et
+but now subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ and $0\leq\lambda_i \leq C$.
+We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads
+!bt
+\[
+\lambda_i\left[y_i(\bm{w}^T\bm{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i,
+\]
+!et
+!bt
+\[
+\gamma_i\xi_i = 0,
+\]
+!et
+and
+!bt
+\[
+y_i(\bm{w}^T\bm{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i.
+\]
+!et
+
+!split
+===== Kernels and non-linearity =====
+
+The cases we have studied till now, were all characterized by two classes
+with a close to linear separability. The classifiers we have described
+so far find linear boundaries in our input feature space. It is
+possible to make our procedure more flexible by exploring the feature
+space using other basis expansions such as higher-order polynomials,
+wavelets, splines etc.
+
+If our feature space is not easy to separate, as shown in the figure
+here, we can achieve a better separation by introducing more complex
+basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to
+obtain a separation between the classes which is almost linear.
+
+The change of basis, from $x\rightarrow z=\phi(x)$ leads to the same type of equations to be solved, except that
+we need to introduce for example a polynomial transformation to a two-dimensional training set.
+
+!bc pycod
+import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+!ec
+
+
+
+!split
+===== The equations =====
+
+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with $x_i$ and $y_i$ as variables)
+!bt
+\[
+z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right).
+\]
+!et
+
+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors
+!bt
+\[
+y_i(\bm{w}^T\bm{z}_i+b)= 1 \hspace{0.1cm}\forall i,
+\]
+!et
+from which we also find $b$.
+To compute $\bm{z}_i^T\bm{z}_j$ we define the kernel $K(\bm{x}_i,\bm{x}_j)$ as
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=\bm{z}_i^T\bm{z}_j= \phi(\bm{x}_i)^T\phi(\bm{x}_j).
+\]
+!et
+For the above example, the kernel reads
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.
+\]
+!et
+
+We note that this is nothing but the dot product of the two original
+vectors $(\bm{x}_i^T\bm{x}_j)^2$. Instead of thus computing the
+product in the Lagrangian of $\bm{z}_i^T\bm{z}_j$ we simply compute
+the dot product $(\bm{x}_i^T\bm{x}_j)^2$.
+
+
+This leads to the so-called
+kernel trick and the result leads to the same as if we went through
+the trouble of performing the transformation
+$\phi(\bm{x}_i)^T\phi(\bm{x}_j)$ during the SVM calculations.
+
+
+!split
+===== The problem to solve =====
+Using our definition of the kernel We can rewrite again the Lagrangian
+!bt
+\[
+{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{z}_j,
+\]
+!et
+subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
+y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
+\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+If we add the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
+
+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type
+!bt
+\begin{align*}
+ &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \hspace{0.2cm} \wedge \bm{A}\bm{\lambda}=f.
+\end{align*}
+!et
+Below we discuss how to solve these equations. Here we note that the matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$.
+Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. How to set up the matrix $\bm{G}$ is discussed later. Here note that the inequalities $0\leq \lambda_i \leq C$ can be split up into
+$0\leq \lambda_i$ and $\lambda_i \leq C$. These two inequalities define then the matrix $\bm{G}$ and the vector $\bm{h}$.
+
+
+!split
+===== Different kernels and Mercer's theorem =====
+
+There are several popular kernels being used. These are
+o Linear: $K(\bm{x},\bm{y})=\bm{x}^T\bm{y}$,
+o Polynomial: $K(\bm{x},\bm{y})=(\bm{x}^T\bm{y}+\gamma)^d$,
+o Gaussian Radial Basis Function: $K(\bm{x},\bm{y})=\exp{\left(-\gamma\vert\vert\bm{x}-\bm{y}\vert\vert^2\right)}$,
+o Tanh: $K(\bm{x},\bm{y})=\tanh{(\bm{x}^T\bm{y}+\gamma)}$,
+and many other ones.
+
+An important theorem for us is "Mercer's
+theorem":"https://en.wikipedia.org/wiki/Mercer%27s_theorem". The
+theorem states that if a kernel function $K$ is symmetric, continuous
+and leads to a positive semi-definite matrix $\bm{P}$ then there
+exists a function $\phi$ that maps $\bm{x}_i$ and $\bm{x}_j$ into
+another space (possibly with much higher dimensions) such that
+
+!bt
+\[
+K(\bm{x}_i,\bm{x}_j)=\phi(\bm{x}_i)^T\phi(\bm{x}_j).
+\]
+!et
+
+So you can use $K$ as a kernel since you know $\phi$ exists, even if
+you don’t know what $\phi$ is.
+
+Note that some frequently used kernels (such as the Sigmoid kernel)
+don’t respect all of Mercer’s conditions, yet they generally work well
+in practice.
+
+
+!split
+===== The moons example =====
+!bc pycod
+from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+ plt.axis(axes)
+ plt.grid(True, which='both')
+ plt.xlabel(r"$x_1$", fontsize=20)
+ plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+ ("poly_features", PolynomialFeatures(degree=3)),
+ ("scaler", StandardScaler()),
+ ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+ ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+ x0s = np.linspace(axes[0], axes[1], 100)
+ x1s = np.linspace(axes[2], axes[3], 100)
+ x0, x1 = np.meshgrid(x0s, x1s)
+ X = np.c_[x0.ravel(), x1.ravel()]
+ y_pred = clf.predict(X).reshape(x0.shape)
+ y_decision = clf.decision_function(X).reshape(x0.shape)
+ plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+ plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+ ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+ ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+ return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+ xy=(X1D[3, 0], 0),
+ xytext=(-0.5, 0.20),
+ ha="center",
+ arrowprops=dict(facecolor='black', shrink=0.1),
+ fontsize=18,
+ )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$ ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+ xy=(XK[3, 0], XK[3, 1]),
+ xytext=(0.65, 0.50),
+ ha="center",
+ arrowprops=dict(facecolor='black', shrink=0.1),
+ fontsize=18,
+ )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+ k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+ print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+ ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+ rbf_kernel_svm_clf = Pipeline([
+ ("scaler", StandardScaler()),
+ ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+ ])
+ rbf_kernel_svm_clf.fit(X, y)
+ svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+ plt.subplot(221 + i)
+ plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+ plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+ gamma, C = hyperparams[i]
+ plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+!ec
+
+
+
+!split
+===== Mathematical optimization of convex functions =====
+
+A mathematical (quadratic) optimization problem, or just optimization problem, has the form
+!bt
+\begin{align*}
+ &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f.
+\end{align*}
+!et
+subject to some constraints for say a selected set $i=1,2,\dots, n$.
+In our case we are optimizing with respect to the Lagrangian multipliers $\lambda_i$, and the
+vector $\bm{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n]$ is the optimization variable we are dealing with.
+
+In our case we are particularly interested in a class of optimization problems called convex optmization problems.
+In our discussion on gradient descent methods we discussed at length the definition of a convex function.
+
+Convex optimization problems play a central role in applied mathematics and we recommend strongly "Boyd and Vandenberghe's text on the topics":"http://web.stanford.edu/~boyd/cvxbook/".
+
+
+
+!split
+===== How do we solve these problems? =====
+
+If we use Python as programming language and wish to venture beyond
+_scikit-learn_, _tensorflow_ and similar software which makes our
+lives so much easier, we need to dive into the wonderful world of
+quadratic programming. We can, if we wish, solve the minimization
+problem using say standard gradient methods or conjugate gradient
+methods. However, these methods tend to exhibit a rather slow
+converge. So, welcome to the promised land of quadratic programming.
+
+The functions we need are contained in the quadratic programming package _CVXOPT_ and we need to import it together with _numpy_ as
+
+!bc pycod
+import numpy
+import cvxopt
+!ec
+
+This will make our life much easier. You don't need t write your own optimizer.
+
+
+!split
+===== A simple example =====
+
+We remind ourselves about the general problem we want to solve
+!bt
+\begin{align*}
+ &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\bm{x}^T\bm{P}\bm{x}+\bm{q}^T\bm{x},\\ \nonumber
+ &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \bm{G}\bm{x} \preceq \bm{h} \wedge \bm{A}\bm{x}=f.
+\end{align*}
+!et
+
+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem
+!bt
+\begin{align*}
+ &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber
+ &\mathrm{subject to} \\ \nonumber
+ &x, y \geq 0 \\ \nonumber
+ &x+3y \geq 15 \\ \nonumber
+ &2x+5y \leq 100 \\ \nonumber
+ &3x+4y \leq 80. \\ \nonumber
+\end{align*}
+!et
+The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)
+!bt
+\[
+\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}.
+\]
+!et
+Similarly, we can now set up the inequalities (we need to change $\geq$ to $\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation
+!bt
+\[
+\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
+\]
+!et
+We have collapsed all the inequalities into a single matrix $\bm{G}$. We see also that our matrix
+!bt
+\[
+\bm{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix}
+\]
+!et
+is clearly positive semi-definite (all eigenvalues larger or equal zero).
+Finally, the vector $\bm{h}$ is defined as
+!bt
+\[
+\bm{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
+\]
+!et
+
+
+Since we don't have any equalities the matrix $\bm{A}$ is set to zero
+The following code solves the equations for us
+!bc pycod
+# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’]
+sol[’primal objective’]
+!ec
+
+!split
+===== Back to the more realistic cases =====
+
+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the _slack_ parameter $C$ we have
+!bt
+\[
+\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
+y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2K(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
+\dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots \\
+y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
+\end{bmatrix}\bm{\lambda}-\mathbb{I}\bm{\lambda},
+\]
+!et
+subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
+$\bm{y}=[y_1,y_2,\dots,y_n]$.
+With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
+
+_code will be added_
+
+