diff --git a/doc/LectureNotes/DataFiles/cancer.dot b/doc/LectureNotes/DataFiles/cancer.dot
index ff048fa30..cfa886d17 100644
--- a/doc/LectureNotes/DataFiles/cancer.dot
+++ b/doc/LectureNotes/DataFiles/cancer.dot
@@ -6,17 +6,17 @@ edge [fontname="helvetica"] ;
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="#e78946"] ;
1 -> 2 ;
-3 [label="area error <= 48.975\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e5833c"] ;
+3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e5833c"] ;
2 -> 3 ;
4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139"] ;
3 -> 4 ;
-5 [label="area error <= 51.38\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#fdf6f0"] ;
+5 [label="mean perimeter <= 78.51\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#fdf6f0"] ;
3 -> 5 ;
6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139"] ;
5 -> 6 ;
7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139"] ;
5 -> 7 ;
-8 [label="worst texture <= 29.455\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#fae9dd"] ;
+8 [label="mean texture <= 20.84\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#fae9dd"] ;
2 -> 8 ;
9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139"] ;
8 -> 9 ;
@@ -34,7 +34,7 @@ edge [fontname="helvetica"] ;
14 -> 15 ;
16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139"] ;
15 -> 16 ;
-17 [label="mean concavity <= 0.07\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#f6d5bd"] ;
+17 [label="worst perimeter <= 115.95\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#f6d5bd"] ;
15 -> 17 ;
18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ;
17 -> 18 ;
@@ -48,10 +48,10 @@ edge [fontname="helvetica"] ;
21 -> 22 ;
23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139"] ;
21 -> 23 ;
-24 [label="mean smoothness <= 0.079\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e6853f"] ;
+24 [label="fractal dimension error <= 0.013\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e6853f"] ;
20 -> 24 ;
-25 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ;
+25 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139"] ;
24 -> 25 ;
-26 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139"] ;
+26 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ;
24 -> 26 ;
}
\ No newline at end of file
diff --git a/doc/LectureNotes/_build/.doctrees/chapter1.doctree b/doc/LectureNotes/_build/.doctrees/chapter1.doctree
index a4e0126a8..1086a5888 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter1.doctree and b/doc/LectureNotes/_build/.doctrees/chapter1.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter10.doctree b/doc/LectureNotes/_build/.doctrees/chapter10.doctree
index 2f4a78ce3..29cd6c4a6 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter10.doctree and b/doc/LectureNotes/_build/.doctrees/chapter10.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter11.doctree b/doc/LectureNotes/_build/.doctrees/chapter11.doctree
index 20082b834..8037b99f9 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter11.doctree and b/doc/LectureNotes/_build/.doctrees/chapter11.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter2.doctree b/doc/LectureNotes/_build/.doctrees/chapter2.doctree
index 13ab170bf..9b17d0f41 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter2.doctree and b/doc/LectureNotes/_build/.doctrees/chapter2.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter3.doctree b/doc/LectureNotes/_build/.doctrees/chapter3.doctree
index c31f4e8c8..879d5ebde 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter3.doctree and b/doc/LectureNotes/_build/.doctrees/chapter3.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter5.doctree b/doc/LectureNotes/_build/.doctrees/chapter5.doctree
index 8785baaae..bd7aca63f 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter5.doctree and b/doc/LectureNotes/_build/.doctrees/chapter5.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter6.doctree b/doc/LectureNotes/_build/.doctrees/chapter6.doctree
index 12d8d7db5..a717ea346 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter6.doctree and b/doc/LectureNotes/_build/.doctrees/chapter6.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter7.doctree b/doc/LectureNotes/_build/.doctrees/chapter7.doctree
index 6edae99eb..f3ddcceb2 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter7.doctree and b/doc/LectureNotes/_build/.doctrees/chapter7.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter8.doctree b/doc/LectureNotes/_build/.doctrees/chapter8.doctree
index 907366060..0edc2d7fa 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter8.doctree and b/doc/LectureNotes/_build/.doctrees/chapter8.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapteroptimization.doctree b/doc/LectureNotes/_build/.doctrees/chapteroptimization.doctree
index 484cd43c0..322d1fe10 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapteroptimization.doctree and b/doc/LectureNotes/_build/.doctrees/chapteroptimization.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/environment.pickle b/doc/LectureNotes/_build/.doctrees/environment.pickle
new file mode 100644
index 000000000..09789998a
Binary files /dev/null and b/doc/LectureNotes/_build/.doctrees/environment.pickle differ
diff --git a/doc/LectureNotes/_build/.doctrees/glue_cache.json b/doc/LectureNotes/_build/.doctrees/glue_cache.json
new file mode 100644
index 000000000..9e26dfeeb
--- /dev/null
+++ b/doc/LectureNotes/_build/.doctrees/glue_cache.json
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/doc/LectureNotes/_build/.doctrees/intro.doctree b/doc/LectureNotes/_build/.doctrees/intro.doctree
index e40874d5c..7f74a1532 100644
Binary files a/doc/LectureNotes/_build/.doctrees/intro.doctree and b/doc/LectureNotes/_build/.doctrees/intro.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/linalg.doctree b/doc/LectureNotes/_build/.doctrees/linalg.doctree
index cae1096c0..3cb2eae6f 100644
Binary files a/doc/LectureNotes/_build/.doctrees/linalg.doctree and b/doc/LectureNotes/_build/.doctrees/linalg.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/statistics.doctree b/doc/LectureNotes/_build/.doctrees/statistics.doctree
index 123f589f8..1a0ee4126 100644
Binary files a/doc/LectureNotes/_build/.doctrees/statistics.doctree and b/doc/LectureNotes/_build/.doctrees/statistics.doctree differ
diff --git a/doc/LectureNotes/_build/html/.buildinfo b/doc/LectureNotes/_build/html/.buildinfo
new file mode 100644
index 000000000..3f46e6780
--- /dev/null
+++ b/doc/LectureNotes/_build/html/.buildinfo
@@ -0,0 +1,4 @@
+# Sphinx build info version 1
+# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
+config: 2fd3d019b83b9c58018e90b52a9aa1b0
+tags: 645f666f9bcd5a90fca523b33c5a78b7
diff --git a/doc/LectureNotes/_build/html/_images/chapter10_33_1.png b/doc/LectureNotes/_build/html/_images/chapter10_33_1.png
new file mode 100644
index 000000000..91a4496c5
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter10_33_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter10_49_1.png b/doc/LectureNotes/_build/html/_images/chapter10_49_1.png
new file mode 100644
index 000000000..6d1467029
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter10_49_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter10_49_2.png b/doc/LectureNotes/_build/html/_images/chapter10_49_2.png
new file mode 100644
index 000000000..b7c47b451
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter10_49_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter10_53_0.png b/doc/LectureNotes/_build/html/_images/chapter10_53_0.png
new file mode 100644
index 000000000..59f332230
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter10_53_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter10_53_1.png b/doc/LectureNotes/_build/html/_images/chapter10_53_1.png
new file mode 100644
index 000000000..10b90707a
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter10_53_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter11_47_2.png b/doc/LectureNotes/_build/html/_images/chapter11_47_2.png
new file mode 100644
index 000000000..5742598bc
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter11_47_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_11_0.png b/doc/LectureNotes/_build/html/_images/chapter1_11_0.png
new file mode 100644
index 000000000..6ec4891e5
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_11_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_136_0.png b/doc/LectureNotes/_build/html/_images/chapter1_136_0.png
new file mode 100644
index 000000000..300291c95
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_136_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_13_1.png b/doc/LectureNotes/_build/html/_images/chapter1_13_1.png
new file mode 100644
index 000000000..9c18773c1
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_13_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_183_1.png b/doc/LectureNotes/_build/html/_images/chapter1_183_1.png
new file mode 100644
index 000000000..87290a7e6
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_183_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_199_1.png b/doc/LectureNotes/_build/html/_images/chapter1_199_1.png
new file mode 100644
index 000000000..29c8b15ab
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_199_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_201_1.png b/doc/LectureNotes/_build/html/_images/chapter1_201_1.png
new file mode 100644
index 000000000..b42fbb010
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_201_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_203_0.png b/doc/LectureNotes/_build/html/_images/chapter1_203_0.png
new file mode 100644
index 000000000..8feaad497
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_203_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_210_0.png b/doc/LectureNotes/_build/html/_images/chapter1_210_0.png
new file mode 100644
index 000000000..04fd4f856
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_210_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_218_0.png b/doc/LectureNotes/_build/html/_images/chapter1_218_0.png
new file mode 100644
index 000000000..b7762d17b
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_218_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_27_0.png b/doc/LectureNotes/_build/html/_images/chapter1_27_0.png
new file mode 100644
index 000000000..a30513b46
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_27_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_3_0.png b/doc/LectureNotes/_build/html/_images/chapter1_3_0.png
new file mode 100644
index 000000000..7ee1932ad
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_3_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_57_1.png b/doc/LectureNotes/_build/html/_images/chapter1_57_1.png
new file mode 100644
index 000000000..ec9a02cf2
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_57_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_59_0.png b/doc/LectureNotes/_build/html/_images/chapter1_59_0.png
new file mode 100644
index 000000000..b54e282f9
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_59_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_61_12.png b/doc/LectureNotes/_build/html/_images/chapter1_61_12.png
new file mode 100644
index 000000000..aa01e9f7d
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_61_12.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter2_245_1.png b/doc/LectureNotes/_build/html/_images/chapter2_245_1.png
new file mode 100644
index 000000000..d53053632
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter2_245_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter2_247_1.png b/doc/LectureNotes/_build/html/_images/chapter2_247_1.png
new file mode 100644
index 000000000..78db82472
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter2_247_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter2_249_1.png b/doc/LectureNotes/_build/html/_images/chapter2_249_1.png
new file mode 100644
index 000000000..cc281a58f
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter2_249_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_107_1.png b/doc/LectureNotes/_build/html/_images/chapter3_107_1.png
new file mode 100644
index 000000000..5de46e7ee
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_107_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_115_1.png b/doc/LectureNotes/_build/html/_images/chapter3_115_1.png
new file mode 100644
index 000000000..57716b7b0
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_115_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_117_1.png b/doc/LectureNotes/_build/html/_images/chapter3_117_1.png
new file mode 100644
index 000000000..92506af14
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_117_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_148_1.png b/doc/LectureNotes/_build/html/_images/chapter3_148_1.png
new file mode 100644
index 000000000..0da8fb2fb
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_148_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_166_1.png b/doc/LectureNotes/_build/html/_images/chapter3_166_1.png
new file mode 100644
index 000000000..f4d12d97a
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_166_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_169_1.png b/doc/LectureNotes/_build/html/_images/chapter3_169_1.png
new file mode 100644
index 000000000..cdf0ad5dc
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_169_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_173_1.png b/doc/LectureNotes/_build/html/_images/chapter3_173_1.png
new file mode 100644
index 000000000..54c39fda5
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_173_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_175_13.png b/doc/LectureNotes/_build/html/_images/chapter3_175_13.png
new file mode 100644
index 000000000..f4d2dc749
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_175_13.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_177_0.png b/doc/LectureNotes/_build/html/_images/chapter3_177_0.png
new file mode 100644
index 000000000..0a2220357
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_177_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_181_1.png b/doc/LectureNotes/_build/html/_images/chapter3_181_1.png
new file mode 100644
index 000000000..b83e84982
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_181_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_47_0.png b/doc/LectureNotes/_build/html/_images/chapter3_47_0.png
new file mode 100644
index 000000000..c2b3c6927
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_47_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_61_1.png b/doc/LectureNotes/_build/html/_images/chapter3_61_1.png
new file mode 100644
index 000000000..f9d994e4b
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_61_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_62_5.png b/doc/LectureNotes/_build/html/_images/chapter3_62_5.png
new file mode 100644
index 000000000..a10a54993
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_62_5.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_64_1.png b/doc/LectureNotes/_build/html/_images/chapter3_64_1.png
new file mode 100644
index 000000000..51bed3706
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_64_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_65_16.png b/doc/LectureNotes/_build/html/_images/chapter3_65_16.png
new file mode 100644
index 000000000..8c55a49e9
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_65_16.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_71_0.png b/doc/LectureNotes/_build/html/_images/chapter3_71_0.png
new file mode 100644
index 000000000..505b245ce
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_71_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_73_1.png b/doc/LectureNotes/_build/html/_images/chapter3_73_1.png
new file mode 100644
index 000000000..dec62c9f9
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_73_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_13_0.png b/doc/LectureNotes/_build/html/_images/chapter4_13_0.png
new file mode 100644
index 000000000..44b37ff30
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_13_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_13_1.png b/doc/LectureNotes/_build/html/_images/chapter4_13_1.png
new file mode 100644
index 000000000..4176f89db
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_13_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_13_2.png b/doc/LectureNotes/_build/html/_images/chapter4_13_2.png
new file mode 100644
index 000000000..198de6994
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_13_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_51_0.png b/doc/LectureNotes/_build/html/_images/chapter4_51_0.png
new file mode 100644
index 000000000..c3b6498c5
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_51_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_51_1.png b/doc/LectureNotes/_build/html/_images/chapter4_51_1.png
new file mode 100644
index 000000000..a724a04f1
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_51_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_57_2.png b/doc/LectureNotes/_build/html/_images/chapter4_57_2.png
new file mode 100644
index 000000000..3baa00e8b
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_57_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_57_3.png b/doc/LectureNotes/_build/html/_images/chapter4_57_3.png
new file mode 100644
index 000000000..1af159ab1
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_57_3.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_57_4.png b/doc/LectureNotes/_build/html/_images/chapter4_57_4.png
new file mode 100644
index 000000000..8305ed433
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_57_4.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_5_1.png b/doc/LectureNotes/_build/html/_images/chapter4_5_1.png
new file mode 100644
index 000000000..cee65bae9
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_5_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter4_7_0.png b/doc/LectureNotes/_build/html/_images/chapter4_7_0.png
new file mode 100644
index 000000000..c4668ff09
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter4_7_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_109_0.png b/doc/LectureNotes/_build/html/_images/chapter5_109_0.png
new file mode 100644
index 000000000..b1023365e
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_109_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_129_0.png b/doc/LectureNotes/_build/html/_images/chapter5_129_0.png
new file mode 100644
index 000000000..3348a8227
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_129_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_129_2.png b/doc/LectureNotes/_build/html/_images/chapter5_129_2.png
new file mode 100644
index 000000000..aeb533770
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_129_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_129_3.png b/doc/LectureNotes/_build/html/_images/chapter5_129_3.png
new file mode 100644
index 000000000..85dec16bb
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_129_3.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_129_4.png b/doc/LectureNotes/_build/html/_images/chapter5_129_4.png
new file mode 100644
index 000000000..25457b8da
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_129_4.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_129_6.png b/doc/LectureNotes/_build/html/_images/chapter5_129_6.png
new file mode 100644
index 000000000..63cefda04
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_129_6.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter5_1_1.png b/doc/LectureNotes/_build/html/_images/chapter5_1_1.png
new file mode 100644
index 000000000..a323677c8
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter5_1_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter6_1_1.png b/doc/LectureNotes/_build/html/_images/chapter6_1_1.png
new file mode 100644
index 000000000..bc1b5ac0a
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter6_1_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter6_1_2.png b/doc/LectureNotes/_build/html/_images/chapter6_1_2.png
new file mode 100644
index 000000000..70faa0954
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter6_1_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter6_24_1.png b/doc/LectureNotes/_build/html/_images/chapter6_24_1.png
new file mode 100644
index 000000000..572004dc7
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter6_24_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter8_65_1.png b/doc/LectureNotes/_build/html/_images/chapter8_65_1.png
new file mode 100644
index 000000000..ff5acf7c3
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter8_65_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter9_29_0.png b/doc/LectureNotes/_build/html/_images/chapter9_29_0.png
new file mode 100644
index 000000000..365106fcf
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter9_29_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter9_29_1.png b/doc/LectureNotes/_build/html/_images/chapter9_29_1.png
new file mode 100644
index 000000000..4e4f7be0e
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter9_29_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter9_29_2.png b/doc/LectureNotes/_build/html/_images/chapter9_29_2.png
new file mode 100644
index 000000000..eb25b37cc
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter9_29_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter9_29_3.png b/doc/LectureNotes/_build/html/_images/chapter9_29_3.png
new file mode 100644
index 000000000..5596de430
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter9_29_3.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_118_2.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_118_2.png
new file mode 100644
index 000000000..4a253c5b3
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_118_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_127_1.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_127_1.png
new file mode 100644
index 000000000..d6601382e
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_127_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_141_2.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_141_2.png
new file mode 100644
index 000000000..48ade4998
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_141_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_177_0.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_177_0.png
new file mode 100644
index 000000000..1e983bdb8
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_177_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_56_2.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_56_2.png
new file mode 100644
index 000000000..7d78856da
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_56_2.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_58_0.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_58_0.png
new file mode 100644
index 000000000..b1441ecf4
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_58_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapteroptimization_64_1.png b/doc/LectureNotes/_build/html/_images/chapteroptimization_64_1.png
new file mode 100644
index 000000000..eeca55933
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapteroptimization_64_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/statistics_178_0.png b/doc/LectureNotes/_build/html/_images/statistics_178_0.png
new file mode 100644
index 000000000..c2be98233
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/statistics_178_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/statistics_184_1.png b/doc/LectureNotes/_build/html/_images/statistics_184_1.png
new file mode 100644
index 000000000..9eb562e57
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/statistics_184_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/statistics_29_0.png b/doc/LectureNotes/_build/html/_images/statistics_29_0.png
new file mode 100644
index 000000000..2a75a0751
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/statistics_29_0.png differ
diff --git a/doc/LectureNotes/_build/html/_sources/chapter1.ipynb b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb
new file mode 100644
index 000000000..d2273f8f7
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb
@@ -0,0 +1,3724 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Linear Regression\n",
+ "\n",
+ "\n",
+ "## Introduction\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Our emphasis throughout this series of lectures is on understanding\n",
+ "the mathematical aspects of different algorithms used in the fields of\n",
+ "data analysis and machine learning.\n",
+ "\n",
+ "However, where possible we will emphasize the importance of using\n",
+ "available software. We start thus with a hands-on and top-down\n",
+ "approach to machine learning. The aim is thus to start with relevant\n",
+ "data or data we have produced and use these to introduce statistical\n",
+ "data analysis concepts and machine learning algorithms before we delve\n",
+ "into the algorithms themselves. The examples we will use in the\n",
+ "beginning, start with simple polynomials with random noise added. We\n",
+ "will use the Python software package\n",
+ "[Scikit-Learn](http://scikit-learn.org/stable/) and introduce various\n",
+ "machine learning algorithms to make fits of the data and\n",
+ "predictions. We move thereafter to more interesting cases such as data\n",
+ "from say experiments (below we will look at experimental nuclear\n",
+ "binding energies as an example). These are examples where we can\n",
+ "easily set up the data and then use machine learning algorithms\n",
+ "included in for example **Scikit-Learn**.\n",
+ "\n",
+ "These examples will serve us the purpose of getting\n",
+ "started. Furthermore, they allow us to catch more than two birds with\n",
+ "a stone. They will allow us to bring in some programming specific\n",
+ "topics and tools as well as showing the power of various Python\n",
+ "libraries for machine learning and statistical data analysis.\n",
+ "\n",
+ "Here, we will mainly focus on two specific Python packages for Machine\n",
+ "Learning, Scikit-Learn and Tensorflow (see below for links etc).\n",
+ "Moreover, the examples we introduce will serve as inputs to many of\n",
+ "our discussions later, as well as allowing you to set up models and\n",
+ "produce your own data and get started with programming.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## What is Machine Learning?\n",
+ "\n",
+ "Statistics, data science and machine learning form important fields of\n",
+ "research in modern science. They describe how to learn and make\n",
+ "predictions from data, as well as allowing us to extract important\n",
+ "correlations about physical process and the underlying laws of motion\n",
+ "in large data sets. The latter, big data sets, appear frequently in\n",
+ "essentially all disciplines, from the traditional Science, Technology,\n",
+ "Mathematics and Engineering fields to Life Science, Law, education\n",
+ "research, the Humanities and the Social Sciences. \n",
+ "\n",
+ "It has become more\n",
+ "and more common to see research projects on big data in for example\n",
+ "the Social Sciences where extracting patterns from complicated survey\n",
+ "data is one of many research directions. Having a solid grasp of data\n",
+ "analysis and machine learning is thus becoming central to scientific\n",
+ "computing in many fields, and competences and skills within the fields\n",
+ "of machine learning and scientific computing are nowadays strongly\n",
+ "requested by many potential employers. The latter cannot be\n",
+ "overstated, familiarity with machine learning has almost become a\n",
+ "prerequisite for many of the most exciting employment opportunities,\n",
+ "whether they are in bioinformatics, life science, physics or finance,\n",
+ "in the private or the public sector. This author has had several\n",
+ "students or met students who have been hired recently based on their\n",
+ "skills and competences in scientific computing and data science, often\n",
+ "with marginal knowledge of machine learning.\n",
+ "\n",
+ "Machine learning is a subfield of computer science, and is closely\n",
+ "related to computational statistics. It evolved from the study of\n",
+ "pattern recognition in artificial intelligence (AI) research, and has\n",
+ "made contributions to AI tasks like computer vision, natural language\n",
+ "processing and speech recognition. Many of the methods we will study are also \n",
+ "strongly rooted in basic mathematics and physics research. \n",
+ "\n",
+ "Ideally, machine learning represents the science of giving computers\n",
+ "the ability to learn without being explicitly programmed. The idea is\n",
+ "that there exist generic algorithms which can be used to find patterns\n",
+ "in a broad class of data sets without having to write code\n",
+ "specifically for each problem. The algorithm will build its own logic\n",
+ "based on the data. You should however always keep in mind that\n",
+ "machines and algorithms are to a large extent developed by humans. The\n",
+ "insights and knowledge we have about a specific system, play a central\n",
+ "role when we develop a specific machine learning algorithm. \n",
+ "\n",
+ "Machine learning is an extremely rich field, in spite of its young\n",
+ "age. The increases we have seen during the last three decades in\n",
+ "computational capabilities have been followed by developments of\n",
+ "methods and techniques for analyzing and handling large date sets,\n",
+ "relying heavily on statistics, computer science and mathematics. The\n",
+ "field is rather new and developing rapidly. Popular software packages\n",
+ "written in Python for machine learning like\n",
+ "[Scikit-learn](http://scikit-learn.org/stable/),\n",
+ "[Tensorflow](https://www.tensorflow.org/),\n",
+ "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n",
+ "freely available at their respective GitHub sites, encompass\n",
+ "communities of developers in the thousands or more. And the number of\n",
+ "code developers and contributors keeps increasing. Not all the\n",
+ "algorithms and methods can be given a rigorous mathematical\n",
+ "justification, opening up thereby large rooms for experimenting and\n",
+ "trial and error and thereby exciting new developments. However, a\n",
+ "solid command of linear algebra, multivariate theory, probability\n",
+ "theory, statistical data analysis, understanding errors and Monte\n",
+ "Carlo methods are central elements in a proper understanding of many\n",
+ "of algorithms and methods we will discuss.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The approaches to machine learning are many, but are often split into\n",
+ "two main categories. In *supervised learning* we know the answer to a\n",
+ "problem, and let the computer deduce the logic behind it. On the other\n",
+ "hand, *unsupervised learning* is a method for finding patterns and\n",
+ "relationship in data sets without any prior knowledge of the system.\n",
+ "Some authours also operate with a third category, namely\n",
+ "*reinforcement learning*. This is a paradigm of learning inspired by\n",
+ "behavioral psychology, where learning is achieved by trial-and-error,\n",
+ "solely from rewards and punishment.\n",
+ "\n",
+ "Another way to categorize machine learning tasks is to consider the\n",
+ "desired output of a system. Some of the most common tasks are:\n",
+ "\n",
+ " * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n",
+ "\n",
+ " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n",
+ "\n",
+ " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n",
+ "\n",
+ "The methods we cover have three main topics in common, irrespective of\n",
+ "whether we deal with supervised or unsupervised learning.\n",
+ "* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n",
+ "\n",
+ "* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n",
+ "\n",
+ "* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n",
+ "\n",
+ "\n",
+ "\n",
+ "At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n",
+ "\n",
+ "\n",
+ "### A Frequentist approach to data analysis\n",
+ "\n",
+ "When you hear phrases like **predictions and estimations** and\n",
+ "**correlations and causations**, what do you think of? May be you think\n",
+ "of the difference between classifying new data points and generating\n",
+ "new data points.\n",
+ "Or perhaps you consider that correlations represent some kind of symmetric statements like\n",
+ "if $A$ is correlated with $B$, then $B$ is correlated with\n",
+ "$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\n",
+ "necessarily cause $A$.\n",
+ "\n",
+ "These concepts are in some sense the difference between machine\n",
+ "learning and statistics. In machine learning and prediction based\n",
+ "tasks, we are often interested in developing algorithms that are\n",
+ "capable of learning patterns from given data in an automated fashion,\n",
+ "and then using these learned patterns to make predictions or\n",
+ "assessments of newly given data. In many cases, our primary concern\n",
+ "is the quality of the predictions or assessments, and we are less\n",
+ "concerned about the underlying patterns that were learned in order\n",
+ "to make these predictions.\n",
+ "\n",
+ "In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\n",
+ "where the aim is to make predictions and find correlations. We focus\n",
+ "less on for example extracting a probability distribution function (PDF). The PDF can be\n",
+ "used in turn to make estimations and find causations such as given $A$\n",
+ "what is the likelihood of finding $B$.\n",
+ "\n",
+ "\n",
+ "### What is a good model?\n",
+ "\n",
+ "In science and engineering we often end up in situations where we want to infer (or learn) a\n",
+ "quantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n",
+ "\n",
+ "As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\n",
+ "straight line, or if we wish to be more sophisticated to a more complex\n",
+ "function.\n",
+ "\n",
+ "The reason for inferring such a model is that it\n",
+ "serves many useful purposes. On the one hand, the model can reveal information\n",
+ "encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\n",
+ "corelations that relate interesting physics interpretations.\n",
+ "\n",
+ "In addition, it can simplify the representation of the given data set and help\n",
+ "us in making predictions about future data samples.\n",
+ "\n",
+ "A first important consideration to keep in mind is that inferring the *correct* model\n",
+ "for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n",
+ "is that if we are not specific about what we mean by a *correct* model, there\n",
+ "could easily be many different models that fit the given data set *equally well*.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "The central question is this: what leads us to say that a model is correct or\n",
+ "optimal for a given data set? To make the model inference problem well posed, i.e.,\n",
+ "to guarantee that there is a unique optimal model for the given data, we need to\n",
+ "impose additional assumptions or restrictions on the class of models considered. To\n",
+ "this end, we should not be looking for just any model that can describe the data.\n",
+ "Instead, we should look for a **model** $M$ that is the best among a restricted class\n",
+ "of models. In addition, to make the model inference problem computationally\n",
+ "tractable, we need to specify how restricted the class of models needs to be. A\n",
+ "common strategy is to start \n",
+ "with the simplest possible class of models that is just necessary to describe the data\n",
+ "or solve the problem at hand. More precisely, the model class should be rich enough\n",
+ "to contain at least one model that can fit the data to a desired accuracy and yet be\n",
+ "restricted enough that it is relatively simple to find the best model for the given data.\n",
+ "\n",
+ "Thus, the most popular strategy is to start from the\n",
+ "simplest class of models and increase the complexity of the models only when the\n",
+ "simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n",
+ "may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n",
+ "\n",
+ "How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Simple linear regression model using **scikit-learn**\n",
+ "\n",
+ "We start with perhaps our simplest possible example, using\n",
+ "**Scikit-Learn** to perform linear regression analysis on a data set\n",
+ "produced by us.\n",
+ "\n",
+ "What follows is a simple Python code where we have defined a function\n",
+ "$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n",
+ "The numbers in the vector $\\boldsymbol{x}$ are given\n",
+ "by random numbers generated with a uniform distribution with entries\n",
+ "$x_i \\in [0,1]$ (more about probability distribution functions\n",
+ "later). These values are then used to define a function $y(x)$\n",
+ "(tabulated again as a vector) with a linear dependence on $x$ plus a\n",
+ "random noise added via the normal distribution.\n",
+ "\n",
+ "\n",
+ "The Numpy functions are imported used the **import numpy as np**\n",
+ "statement and the random number generator for the uniform distribution\n",
+ "is called using the function **np.random.rand()**, where we specificy\n",
+ "that we want $100$ random variables. Using Numpy we define\n",
+ "automatically an array with the specified number of elements, $100$ in\n",
+ "our case. With the Numpy function **randn()** we can compute random\n",
+ "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n",
+ "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n",
+ "dependence as function of $x$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y = 2x+N(0,1),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $N(0,1)$ represents random numbers generated by the normal\n",
+ "distribution. From **Scikit-Learn** we import then the\n",
+ "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n",
+ "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n",
+ "data $(\\boldsymbol{x},\\boldsymbol{y})$ for our training data. The Python package\n",
+ "**scikit-learn** has also a functionality which extracts the above\n",
+ "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n",
+ "distinguish between training data and test data.\n",
+ "\n",
+ "For plotting we use the Python package\n",
+ "[matplotlib](https://matplotlib.org/) which produces publication\n",
+ "quality figures. Feel free to explore the extensive\n",
+ "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n",
+ "this example we plot our original values of $x$ and $y$ as well as the\n",
+ "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n",
+ "data with a straight line. Note also that **Scikit-Learn** requires a\n",
+ "matrix as input for the input values $x$ and $y$. In the above code we\n",
+ "have solved this by declaring $x$ and $y$ as arrays of dimension\n",
+ "$n\\times 1$.\n",
+ "\n",
+ "In the code here we have also made a new array for $x\\in [0,1]$. Our\n",
+ "prediction is computed for these values, meaning that they were not\n",
+ "included in the data set used to *train* (or fit) the model.\n",
+ "This is a recurrring theme in machine learning and data analysis. We would like to train a model on a specific given data set.\n",
+ "Thereafter we wish to apply it to data which were not included in the training. Below we will encounter this again in the so-called *train-validate-test* spliting. We will typically split our data into different sets, oen for training, one for validation and finally, our data from the untouched test vault!\n",
+ "\n",
+ "\n",
+ "The Python code follows here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "x = np.random.rand(100,1)\n",
+ "y = 2*x+np.random.randn(100,1)\n",
+ "linreg = LinearRegression()\n",
+ "linreg.fit(x,y)\n",
+ "# This is our new x-array to which we test our model\n",
+ "xnew = np.array([[0],[1]])\n",
+ "ypredict = linreg.predict(xnew)\n",
+ "\n",
+ "plt.plot(xnew, ypredict, \"r-\")\n",
+ "plt.plot(x, y ,'ro')\n",
+ "plt.axis([0,1.0,0, 5.0])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$y$')\n",
+ "plt.title(r'Simple Linear Regression')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This example serves several aims. It allows us to demonstrate several\n",
+ "aspects of data analysis and later machine learning algorithms. The\n",
+ "immediate visualization shows that our linear fit is not\n",
+ "impressive. It goes through the data points, but there are many\n",
+ "outliers which are not reproduced by our linear regression. We could\n",
+ "now play around with this small program and change for example the\n",
+ "factor in front of $x$ and the normal distribution. Try to change the\n",
+ "function $y$ to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y = 10x+0.01 \\times N(0,1),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $x$ is defined as before. Does the fit look better? Indeed, by\n",
+ "reducing the role of the noise given by the normal distribution we see immediately that\n",
+ "our linear prediction seemingly reproduces better the training\n",
+ "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n",
+ "long run. Here we have only defined the training data and our model, and \n",
+ "have not discussed a more rigorous approach to the **cost** function.\n",
+ "\n",
+ "We need more rigorous criteria in defining whether we have succeeded or\n",
+ "not in modeling our training data. You will be surprised to see that\n",
+ "many scientists seldomly venture beyond this 'by the eye' approach. A\n",
+ "standard approach for the *cost* function is the so-called $\\chi^2$\n",
+ "function (a variant of the mean-squared error (MSE))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\chi^2 = \\frac{1}{n}\n",
+ "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n",
+ "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n",
+ "however the aim of scaling the equations and make the cost function\n",
+ "dimensionless. \n",
+ "\n",
+ "Minimizing the cost function is a central aspect of\n",
+ "our discussions to come. Finding its minima as function of the model\n",
+ "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n",
+ "theme in these series of lectures. Essentially all machine learning\n",
+ "algorithms we will discuss center around the minimization of the\n",
+ "chosen cost function. This depends in turn on our specific\n",
+ "model for describing the data, a typical situation in supervised\n",
+ "learning. Automatizing the search for the minima of the cost function is a\n",
+ "central ingredient in all algorithms. Typical methods which are\n",
+ "employed are various variants of **gradient** methods. These will be\n",
+ "discussed in more detail later. Again, you'll be surprised to hear that\n",
+ "many practitioners minimize the above function ''by the eye', popularly dubbed as \n",
+ "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n",
+ "the $\\chi^2$ function becomes smaller. \n",
+ "\n",
+ "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n",
+ "the relative error (why would we prefer the MSE instead of the relative error?) as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\boldsymbol{y} -\\boldsymbol{\\tilde{y}}\\vert}{\\vert \\boldsymbol{y}\\vert}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The squared cost function results in an arithmetic mean-unbiased\n",
+ "estimator, and the absolute-value cost function results in a\n",
+ "median-unbiased estimator (in the one-dimensional case, and a\n",
+ "geometric median-unbiased estimator for the multi-dimensional\n",
+ "case). The squared cost function has the disadvantage that it has the tendency\n",
+ "to be dominated by outliers.\n",
+ "\n",
+ "We can modify easily the above Python code and plot the relative error instead"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "# Number of data points\n",
+ "n = 100\n",
+ "x = np.random.rand(100,1)\n",
+ "y = 5*x+0.01*np.random.randn(100,1)\n",
+ "linreg = LinearRegression()\n",
+ "linreg.fit(x,y)\n",
+ "ypredict = linreg.predict(x)\n",
+ "\n",
+ "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n",
+ "plt.axis([0,1.0,0.0, 0.5])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n",
+ "plt.title(r'Relative error')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Depending on the parameter in front of the normal distribution, we may\n",
+ "have a small or larger relative error. Try to play around with\n",
+ "different training data sets and study (graphically) the value of the\n",
+ "relative error.\n",
+ "\n",
+ "As mentioned above, **Scikit-Learn** has an impressive functionality.\n",
+ "We can for example extract the values of $\\alpha$ and $\\beta$ and\n",
+ "their error estimates, or the variance and standard deviation and many\n",
+ "other properties from the statistical data analysis. \n",
+ "\n",
+ "Here we show an\n",
+ "example of the functionality of **Scikit-Learn**."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np \n",
+ "import matplotlib.pyplot as plt \n",
+ "from sklearn.linear_model import LinearRegression \n",
+ "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n",
+ "\n",
+ "x = np.random.rand(100,1)\n",
+ "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n",
+ "linreg = LinearRegression()\n",
+ "linreg.fit(x,y)\n",
+ "ypredict = linreg.predict(x)\n",
+ "print('The intercept alpha: \\n', linreg.intercept_)\n",
+ "print('Coefficient beta : \\n', linreg.coef_)\n",
+ "# The mean squared error \n",
+ "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n",
+ "# Explained variance score: 1 is perfect prediction \n",
+ "print('Variance score: %.2f' % r2_score(y, ypredict))\n",
+ "# Mean squared log error \n",
+ "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n",
+ "# Mean absolute error \n",
+ "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n",
+ "plt.plot(x, ypredict, \"r-\")\n",
+ "plt.plot(x, y ,'ro')\n",
+ "plt.axis([0.0,1.0,1.5, 7.0])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$y$')\n",
+ "plt.title(r'Linear Regression fit ')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n",
+ "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n",
+ "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The smaller the value, the better the fit. Ideally we would like to\n",
+ "have an MSE equal zero. The attentive reader has probably recognized\n",
+ "this function as being similar to the $\\chi^2$ function defined above.\n",
+ "\n",
+ "The **r2score** function computes $R^2$, the coefficient of\n",
+ "determination. It provides a measure of how well future samples are\n",
+ "likely to be predicted by the model. Best possible score is 1.0 and it\n",
+ "can be negative (because the model can be arbitrarily worse). A\n",
+ "constant model that always predicts the expected value of $\\boldsymbol{y}$,\n",
+ "disregarding the input features, would get a $R^2$ score of $0.0$.\n",
+ "\n",
+ "If $\\tilde{\\boldsymbol{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(\\boldsymbol{y}, \\tilde{\\boldsymbol{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 $\\boldsymbol{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": [
+ "Another quantity taht we will meet again in our discussions of regression analysis is \n",
+ " the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n",
+ "The MAE is defined as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\text{MAE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We present the \n",
+ "squared logarithmic (quadratic) error"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\text{MSLE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n",
+ "estimate is best to use when targets having exponential growth, such\n",
+ "as population counts, average sales of a commodity over a span of\n",
+ "years etc. \n",
+ "\n",
+ "\n",
+ "Finally, another cost function is the Huber cost function used in robust regression.\n",
+ "\n",
+ "The rationale behind this possible cost function is its reduced\n",
+ "sensitivity to outliers in the data set. In our discussions on\n",
+ "dimensionality reduction and normalization of data we will meet other\n",
+ "ways of dealing with outliers.\n",
+ "\n",
+ "The Huber cost function is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "H_{\\delta}(\\boldsymbol{a})=\\left\\{\\begin{array}{cc}\\frac{1}{2} \\boldsymbol{a}^{2}& \\text{for }|\\boldsymbol{a}|\\leq \\delta\\\\ \\delta (|\\boldsymbol{a}|-\\frac{1}{2}\\delta ),&\\text{otherwise}.\\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here $\\boldsymbol{a}=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We will discuss in more\n",
+ "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n",
+ "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "import random\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "x=np.linspace(0.02,0.98,200)\n",
+ "noise = np.asarray(random.sample((range(200)),200))\n",
+ "y=x**3*noise\n",
+ "yn=x**3*100\n",
+ "poly3 = PolynomialFeatures(degree=3)\n",
+ "X = poly3.fit_transform(x[:,np.newaxis])\n",
+ "clf3 = LinearRegression()\n",
+ "clf3.fit(X,y)\n",
+ "\n",
+ "Xplot=poly3.fit_transform(x[:,np.newaxis])\n",
+ "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n",
+ "plt.plot(x,yn, color='red', label=\"True Cubic\")\n",
+ "plt.scatter(x, y, label='Data', color='orange', s=15)\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "def error(a):\n",
+ " for i in y:\n",
+ " err=(y-yn)/yn\n",
+ " return abs(np.sum(err))/len(err)\n",
+ "\n",
+ "print (error(y))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\n",
+ "energies. A basic quantity which can be measured for the ground\n",
+ "states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\n",
+ "atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n",
+ "\n",
+ "Atomic masses are usually tabulated in terms of the mass excess defined by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\Delta M(N, Z) = M(N, Z) - uA,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $u$ is the Atomic Mass Unit"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The nucleon masses are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "m_p = 1.00727646693(9)u,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "m_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\n",
+ "there are data on masses and decays of 3437 nuclei.\n",
+ "\n",
+ "The nuclear binding energy is defined as the energy required to break\n",
+ "up a given nucleus into its constituent parts of $N$ neutrons and $Z$\n",
+ "protons. In terms of the atomic masses $M(N, Z)$ the binding energy is\n",
+ "defined by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\n",
+ "In terms of the mass excess the binding energy is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "BE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n",
+ "\n",
+ "\n",
+ "A popular and physically intuitive model which can be used to parametrize \n",
+ "the experimental binding energies as function of $A$, is the so-called \n",
+ "**liquid drop model**. The ansatz is based on the following expression"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "BE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \n",
+ "to the experimental data. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "To arrive at the above expression we have assumed that we can make the following assumptions:\n",
+ "\n",
+ " * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n",
+ "\n",
+ " * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n",
+ "\n",
+ " * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n",
+ "\n",
+ " * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n",
+ "\n",
+ "We could also add a so-called pairing term, which is a correction term that\n",
+ "arises from the tendency of proton pairs and neutron pairs to\n",
+ "occur. An even number of particles is more stable than an odd number. \n",
+ "\n",
+ "\n",
+ "### Organizing our data\n",
+ "\n",
+ "Let us start with reading and organizing our data. \n",
+ "We start with the compilation of masses and binding energies from 2016.\n",
+ "After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n",
+ "\n",
+ "\n",
+ "We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "import sklearn.linear_model as skl\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
+ "import os\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"MassEval2016.dat\"),'r')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various **matplotlib** commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from pylab import plt, mpl\n",
+ "plt.style.use('seaborn')\n",
+ "mpl.rcParams['font.family'] = 'serif'\n",
+ "\n",
+ "def MakePlot(x,y, styles, labels, axlabels):\n",
+ " plt.figure(figsize=(10,6))\n",
+ " for i in range(len(x)):\n",
+ " plt.plot(x[i], y[i], styles[i], label = labels[i])\n",
+ " plt.xlabel(axlabels[0])\n",
+ " plt.ylabel(axlabels[1])\n",
+ " plt.legend(loc=0)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our next step is to read the data on experimental binding energies and\n",
+ "reorganize them as functions of the mass number $A$, the number of\n",
+ "protons $Z$ and neutrons $N$ using **pandas**. Before we do this it is\n",
+ "always useful (unless you have a binary file or other types of compressed\n",
+ "data) to actually open the file and simply take a look at it!\n",
+ "\n",
+ "\n",
+ "In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\" \n",
+ "This is taken from the data file of the mass 2016 evaluation. \n",
+ "All files are 3436 lines long with 124 character per line. \n",
+ " Headers are 39 lines long. \n",
+ " col 1 : Fortran character control: 1 = page feed 0 = line feed \n",
+ " format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n",
+ " These formats are reflected in the pandas widths variable below, see the statement \n",
+ " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n",
+ " Pandas has also a variable header, with length 39 in this case. \n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The data we are interested in are in columns 2, 3, 4 and 11, giving us\n",
+ "the number of neutrons, protons, mass numbers and binding energies,\n",
+ "respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will\n",
+ "covert them into the **pandas** DataFrame structure."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Read the experimental data with Pandas\n",
+ "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
+ " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
+ " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
+ " header=39,\n",
+ " index_col=False)\n",
+ "\n",
+ "# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
+ "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
+ "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
+ "Masses = Masses.dropna()\n",
+ "# Convert from keV to MeV.\n",
+ "Masses['Ebinding'] /= 1000\n",
+ "\n",
+ "# Group the DataFrame by nucleon number, A.\n",
+ "Masses = Masses.groupby('A')\n",
+ "# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
+ "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have now read in the data, grouped them according to the variables we are interested in. \n",
+ "We see how easy it is to reorganize the data using **pandas**. If we\n",
+ "were to do these operations in C/C++ or Fortran, we would have had to\n",
+ "write various functions/subroutines which perform the above\n",
+ "reorganizations for us. Having reorganized the data, we can now start\n",
+ "to make some simple fits using both the functionalities in **numpy** and\n",
+ "**Scikit-Learn** afterwards. \n",
+ "\n",
+ "Now we define five variables which contain\n",
+ "the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "A = Masses['A']\n",
+ "Z = Masses['Z']\n",
+ "N = Masses['N']\n",
+ "Element = Masses['Element']\n",
+ "Energies = Masses['Ebinding']\n",
+ "print(Masses)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The next step, and we will define this mathematically later, is to set up the so-called **design matrix**. We will throughout call this matrix $\\boldsymbol{X}$.\n",
+ "It has dimensionality $n\\times p$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Now we set up the design matrix X\n",
+ "X = np.zeros((len(A),5))\n",
+ "X[:,0] = 1\n",
+ "X[:,1] = A\n",
+ "X[:,2] = A**(2.0/3.0)\n",
+ "X[:,3] = A**(-1.0/3.0)\n",
+ "X[:,4] = A**(-1.0)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note well that we have made life simple here. We perform a fit in\n",
+ "terms of the number of nucleons only. A more sophisticated fit can be\n",
+ "done by including an explicit dependence on the number of protons and\n",
+ "neutrons in the asymmetry and Coulomb terms. We leave this as an exercise to you the reader.\n",
+ "\n",
+ "With **Scikit-Learn** we are now ready to use linear regression and fit our data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "clf = skl.LinearRegression().fit(X, Energies)\n",
+ "fity = clf.predict(X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Pretty simple! \n",
+ "Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# The mean squared error \n",
+ "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n",
+ "# Explained variance score: 1 is perfect prediction \n",
+ "print('Variance score: %.2f' % r2_score(Energies, fity))\n",
+ "# Mean absolute error \n",
+ "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n",
+ "\n",
+ "Masses['Eapprox'] = fity\n",
+ "# Generate a plot comparing the experimental with the fitted values values.\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.set_xlabel(r'$A = N + Z$')\n",
+ "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
+ "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
+ " label='Ame2016')\n",
+ "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
+ " label='Fit')\n",
+ "ax.legend()\n",
+ "save_fig(\"Masses2016\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As a teaser, let us now see how we can do this with decision trees using **Scikit-Learn**. Later we will switch to so-called **random forests**!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "#Decision Tree Regression\n",
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "regr_1=DecisionTreeRegressor(max_depth=5)\n",
+ "regr_2=DecisionTreeRegressor(max_depth=7)\n",
+ "regr_3=DecisionTreeRegressor(max_depth=9)\n",
+ "regr_1.fit(X, Energies)\n",
+ "regr_2.fit(X, Energies)\n",
+ "regr_3.fit(X, Energies)\n",
+ "\n",
+ "\n",
+ "y_1 = regr_1.predict(X)\n",
+ "y_2 = regr_2.predict(X)\n",
+ "y_3=regr_3.predict(X)\n",
+ "Masses['Eapprox'] = y_3\n",
+ "# Plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(A, Energies, color=\"blue\", label=\"Data\", linewidth=2)\n",
+ "plt.plot(A, y_1, color=\"red\", label=\"max_depth=5\", linewidth=2)\n",
+ "plt.plot(A, y_2, color=\"green\", label=\"max_depth=7\", linewidth=2)\n",
+ "plt.plot(A, y_3, color=\"m\", label=\"max_depth=9\", linewidth=2)\n",
+ "\n",
+ "plt.xlabel(\"$A$\")\n",
+ "plt.ylabel(\"$E$[MeV]\")\n",
+ "plt.title(\"Decision Tree Regression\")\n",
+ "plt.legend()\n",
+ "save_fig(\"Masses2016Trees\")\n",
+ "plt.show()\n",
+ "print(Masses)\n",
+ "print(np.mean( (Energies-y_1)**2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With a deeper and deeper tree level, we can almost reproduce every\n",
+ "single data point by increasing the max depth of the tree.\n",
+ "We can actually decide to make a decision tree which fits every single point.\n",
+ "As we will\n",
+ "see later, this has the benefit that we can really train a model which\n",
+ "traverses every single data point. However, the price we pay is that\n",
+ "we will easily overfit. That is, if we apply our model to unseen data,\n",
+ "we will most likely fail miserably in our attempt at making\n",
+ "predictions. As an exercise, try to make the tree level larger by adjusting the maximum depth variable. When printing out the predicition, you will note that the binding energy of every nucleus is accurately reproduced.\n",
+ "\n",
+ "\n",
+ "The **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \n",
+ "functionality."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.neural_network import MLPRegressor\n",
+ "from sklearn.metrics import accuracy_score\n",
+ "import seaborn as sns\n",
+ "\n",
+ "X_train = X\n",
+ "Y_train = Energies\n",
+ "n_hidden_neurons = 100\n",
+ "epochs = 100\n",
+ "# store models for later use\n",
+ "eta_vals = np.logspace(-5, 1, 7)\n",
+ "lmbd_vals = np.logspace(-5, 1, 7)\n",
+ "# store the models for later use\n",
+ "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
+ "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "sns.set()\n",
+ "for i, eta in enumerate(eta_vals):\n",
+ " for j, lmbd in enumerate(lmbd_vals):\n",
+ " dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
+ " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
+ " dnn.fit(X_train, Y_train)\n",
+ " DNN_scikit[i][j] = dnn\n",
+ " train_accuracy[i][j] = dnn.score(X_train, Y_train)\n",
+ "\n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Training Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Linear Regression, basic elements\n",
+ "\n",
+ "\n",
+ "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureAug27.mp4?vrtx=view-as-webpage).\n",
+ "\n",
+ "\n",
+ "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n",
+ "* Method of choice for fitting a continuous function!\n",
+ "\n",
+ "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n",
+ "\n",
+ "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n",
+ "\n",
+ "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n",
+ "\n",
+ "* Analytical relation with probabilistic interpretations \n",
+ "\n",
+ "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n",
+ "\n",
+ "* Easy to code! And links well with classification problems and logistic regression and neural networks\n",
+ "\n",
+ "* Allows for **easy** hands-on understanding of gradient descent methods\n",
+ "\n",
+ "* and many more features\n",
+ "\n",
+ "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
+ "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n",
+ "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n",
+ "\n",
+ "A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n",
+ "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n",
+ "\n",
+ "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n",
+ "\n",
+ "* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n",
+ "\n",
+ " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{x}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.\n",
+ "\n",
+ "\n",
+ "Consider an experiment in which $p$ characteristics of $n$ samples are\n",
+ "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n",
+ "$\\mathbf{X}$.\n",
+ "\n",
+ "The matrix $\\mathbf{X}$ is called the *design\n",
+ "matrix*. Additional information of the samples is available in the\n",
+ "form of $\\boldsymbol{y}$ (also as above). The variable $\\boldsymbol{y}$ is\n",
+ "generally referred to as the *response variable*. The aim of\n",
+ "regression analysis is to explain $\\boldsymbol{y}$ in terms of\n",
+ "$\\boldsymbol{X}$ through a functional relationship like $y_i =\n",
+ "f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n",
+ "$f(\\cdot)$ is available, it is common to assume a linear relationship\n",
+ "between $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n",
+ "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n",
+ "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n",
+ "\n",
+ "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n",
+ "\n",
+ "\n",
+ "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n",
+ "consider the model we discussed for describing nuclear binding energies. \n",
+ "\n",
+ "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n",
+ "Assuming"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n",
+ "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n",
+ "$p\\times n$ matrix $\\boldsymbol{X}$.\n",
+ "\n",
+ "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n",
+ "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression. \n",
+ "\n",
+ "\n",
+ "Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\boldsymbol{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\boldsymbol{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n",
+ "\n",
+ "Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_j x_i^j+\\epsilon_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\epsilon_i$ is the error in our approximation. \n",
+ "\n",
+ "\n",
+ "For every set of values $y_i,x_i$ we have thus the corresponding set of equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "y_0&=\\beta_0+\\beta_1x_0^1+\\beta_2x_0^2+\\dots+\\beta_{n-1}x_0^{n-1}+\\epsilon_0\\\\\n",
+ "y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n",
+ "y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n",
+ "\\dots & \\dots \\\\\n",
+ "y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_{n-1}x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Defining the vectors"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the design matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\n",
+ "\\begin{bmatrix} \n",
+ "1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n",
+ "1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n",
+ "1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n",
+ "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n",
+ "1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite our equations as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n",
+ "\n",
+ "We are obviously not limited to the above polynomial expansions. We\n",
+ "could replace the various powers of $x$ with elements of Fourier\n",
+ "series or instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j\n",
+ "x_i)}$, or time series or other orthogonal functions. For every set\n",
+ "of values $y_i,x_i$ we can then generalize the equations to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n",
+ "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n",
+ "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_2\\\\\n",
+ "\\dots & \\dots \\\\\n",
+ "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n",
+ "\\dots & \\dots \\\\\n",
+ "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**\n",
+ "\n",
+ "We redefine in turn the matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\n",
+ "\\begin{bmatrix} \n",
+ "x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n",
+ "x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n",
+ "x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n",
+ "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n",
+ "x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and without loss of generality we rewrite again our equations as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values? \n",
+ "\n",
+ "We have defined the matrix $\\boldsymbol{X}$ via the equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n",
+ "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n",
+ "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_1\\\\\n",
+ "\\dots & \\dots \\\\\n",
+ "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n",
+ "\\dots & \\dots \\\\\n",
+ "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we noted above, we stayed with a system with the design matrix \n",
+ " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n",
+ "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements.\n",
+ "\n",
+ "In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n",
+ "\n",
+ "We restate the parts of the code we are most interested in."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from IPython.display import display\n",
+ "import os\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"MassEval2016.dat\"),'r')\n",
+ "\n",
+ "\n",
+ "# Read the experimental data with Pandas\n",
+ "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
+ " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
+ " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
+ " header=39,\n",
+ " index_col=False)\n",
+ "\n",
+ "# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
+ "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
+ "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
+ "Masses = Masses.dropna()\n",
+ "# Convert from keV to MeV.\n",
+ "Masses['Ebinding'] /= 1000\n",
+ "\n",
+ "# Group the DataFrame by nucleon number, A.\n",
+ "Masses = Masses.groupby('A')\n",
+ "# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
+ "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n",
+ "A = Masses['A']\n",
+ "Z = Masses['Z']\n",
+ "N = Masses['N']\n",
+ "Element = Masses['Element']\n",
+ "Energies = Masses['Ebinding']\n",
+ "\n",
+ "# Now we set up the design matrix X\n",
+ "X = np.zeros((len(A),5))\n",
+ "X[:,0] = 1\n",
+ "X[:,1] = A\n",
+ "X[:,2] = A**(2.0/3.0)\n",
+ "X[:,3] = A**(-1.0/3.0)\n",
+ "X[:,4] = A**(-1.0)\n",
+ "# Then nice printout using pandas\n",
+ "DesignMatrix = pd.DataFrame(X)\n",
+ "DesignMatrix.index = A\n",
+ "DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n",
+ "display(DesignMatrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "throughout these lectures. \n",
+ "\n",
+ "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\\tilde{y}_i$, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This function is one possible way to define the so-called cost function.\n",
+ "\n",
+ "\n",
+ "\n",
+ "It is also common to define\n",
+ "the function $C$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out. \n",
+ "\n",
+ "The function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n",
+ "When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\n",
+ "till now we have treated $y_i$ as the exact value. Normally, the\n",
+ "response (dependent or outcome) variable $y_i$ the outcome of a\n",
+ "numerical experiment or another type of experiment and is thus only an\n",
+ "approximation to the true value. It is then always accompanied by an\n",
+ "error estimate, often limited to a statistical error estimate given by\n",
+ "the standard deviation discussed earlier. In the discussion here we\n",
+ "will treat $y_i$ as our exact value for the response variable.\n",
+ "\n",
+ "In order to find the parameters $\\beta_i$ we will then minimize the spread of $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In practical terms it means we will require"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or in a matrix-vector form as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n",
+ "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n",
+ "{\\mathbb{R}}^{p\\times p}$. In the above case we have that $p \\ll n$,\n",
+ "in our case $p=5$ meaning that we end up with inverting a small\n",
+ "$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n",
+ "matrices to invert. The methods discussed here and for many other\n",
+ "supervised learning algorithms like classification with logistic\n",
+ "regression or support vector machines, exhibit dimensionalities which\n",
+ "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$. \n",
+ "\n",
+ "**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect? \n",
+ "\n",
+ "\n",
+ "The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and \n",
+ "matrices as upper case boldfaced letters."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "4\n",
+ "3\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "M\n",
+ "A\n",
+ "T\n",
+ "H\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "4\n",
+ "4\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "M\n",
+ "A\n",
+ "T\n",
+ "H\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "4\n",
+ "5\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "M\n",
+ "A\n",
+ "T\n",
+ "H\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial\\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}}=(\\boldsymbol{A}^{-1})^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can then compute the second derivative of the cost function, which in our case is the second derivative\n",
+ "of the means squared error. This leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "\n",
+ "The Hessian matrix plays an important role and is defined for the mean squared error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Hessian matrix for ordinary least squares is also proportional to\n",
+ "the covariance matrix. As we will see in the chapter on Ridge and Lasso regression, This means that we can use the Singular Value Decomposition of a matrix to find\n",
+ "the eigenvalues of the covariance matrix and the Hessian matrix in\n",
+ "terms of the singular values.\n",
+ "\n",
+ "\n",
+ "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n",
+ "\n",
+ "\n",
+ "Let us now return to our nuclear binding energies and simply code the above equations. \n",
+ "\n",
+ "\n",
+ "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n",
+ "write"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# matrix inversion to find beta\n",
+ "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n",
+ "# and then make the prediction\n",
+ "ytilde = X @ beta"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Alternatively, you can use the least squares functionality in **Numpy** as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n",
+ "ytildenp = np.dot(fit,X.T)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And finally we plot our fit with and compare with data"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "Masses['Eapprox'] = ytilde\n",
+ "# Generate a plot comparing the experimental with the fitted values values.\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.set_xlabel(r'$A = N + Z$')\n",
+ "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
+ "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
+ " label='Ame2016')\n",
+ "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
+ " label='Fit')\n",
+ "ax.legend()\n",
+ "save_fig(\"Masses2016OLS\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of **Scikit-Learn** in the introductory slides.\n",
+ "Since we are not using **Scikit-Learn** here we can define our own $R2$ function as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we would be using it as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "print(R2(Energies,ytilde))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can easily add our **MSE** score as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "print(MSE(Energies,ytilde))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and finally the relative error as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "def RelativeError(y_data,y_model):\n",
+ " return abs((y_data-y_model)/y_data)\n",
+ "print(RelativeError(Energies, ytilde))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### The $\\chi^2$ function\n",
+ "\n",
+ "Normally, the response (dependent or outcome) variable $y_i$ is the\n",
+ "outcome of a numerical experiment or another type of experiment and is\n",
+ "thus only an approximation to the true value. It is then always\n",
+ "accompanied by an error estimate, often limited to a statistical error\n",
+ "estimate given by the standard deviation discussed earlier. In the\n",
+ "discussion here we will treat $y_i$ as our exact value for the\n",
+ "response variable.\n",
+ "\n",
+ "Introducing the standard deviation $\\sigma_i$ for each measurement\n",
+ "$y_i$, we define now the $\\chi^2$ function (omitting the $1/n$ term)\n",
+ "as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements. \n",
+ "\n",
+ "\n",
+ "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or in a matrix-vector form as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$. \n",
+ "\n",
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then introduce the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{H}$ are $h_{ij}$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For a linear fit (a first-order polynomial) we don't need to invert a matrix!! \n",
+ "Defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This approach (different linear and non-linear regression) suffers\n",
+ "often from both being underdetermined and overdetermined in the\n",
+ "unknown coefficients $\\beta_i$. A better approach is to use the\n",
+ "Singular Value Decomposition (SVD) method discussed below. Or using\n",
+ "Lasso and Ridge regression. See below.\n",
+ "\n",
+ "\n",
+ "### Fitting an Equation of State for Dense Nuclear Matter\n",
+ "\n",
+ "Before we continue, let us introduce yet another example. We are going to fit the\n",
+ "nuclear equation of state using results from many-body calculations.\n",
+ "The equation of state we have made available here, as function of\n",
+ "density, has been derived using modern nucleon-nucleon potentials with\n",
+ "[the addition of three-body\n",
+ "forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n",
+ "time the file is presented as a standard **csv** file.\n",
+ "\n",
+ "The beginning of the Python code here is similar to what you have seen\n",
+ "before, with the same initializations and declarations. We use also\n",
+ "**pandas** again, rather extensively in order to organize our data.\n",
+ "\n",
+ "The difference now is that we use **Scikit-Learn's** regression tools\n",
+ "instead of our own matrix inversion implementation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "import matplotlib.pyplot as plt\n",
+ "import sklearn.linear_model as skl\n",
+ "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "X = np.zeros((len(Density),4))\n",
+ "X[:,3] = Density**(4.0/3.0)\n",
+ "X[:,2] = Density\n",
+ "X[:,1] = Density**(2.0/3.0)\n",
+ "X[:,0] = 1\n",
+ "\n",
+ "# We use now Scikit-Learn's linear regressor and ridge regressor\n",
+ "# OLS part\n",
+ "clf = skl.LinearRegression().fit(X, Energies)\n",
+ "ytilde = clf.predict(X)\n",
+ "EoS['Eols'] = ytilde\n",
+ "# The mean squared error \n",
+ "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n",
+ "# Explained variance score: 1 is perfect prediction \n",
+ "print('Variance score: %.2f' % r2_score(Energies, ytilde))\n",
+ "# Mean absolute error \n",
+ "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n",
+ "print(clf.coef_, clf.intercept_)\n",
+ "\n",
+ "\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n",
+ "ax.set_ylabel(r'Energy per particle')\n",
+ "ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n",
+ " label='Theoretical data')\n",
+ "ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n",
+ " label='OLS')\n",
+ "ax.legend()\n",
+ "save_fig(\"EoSfitting\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The above simple polynomial in density $\\rho$ gives an excellent fit\n",
+ "to the data. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Splitting our Data in Training and Test data\n",
+ "\n",
+ "\n",
+ "It is normal in essentially all Machine Learning studies to split the\n",
+ "data in a training set and a test set (sometimes also an additional\n",
+ "validation set). **Scikit-Learn** has an own function for this. There\n",
+ "is no explicit recipe for how much data should be included as training\n",
+ "data and say test data. An accepted rule of thumb is to use\n",
+ "approximately $2/3$ to $4/5$ of the data as training data. We will\n",
+ "postpone a discussion of this splitting to the end of these notes and\n",
+ "our discussion of the so-called **bias-variance** tradeoff. Here we\n",
+ "limit ourselves to repeat the above equation of state fitting example\n",
+ "but now splitting the data into a training set and a test set.\n",
+ "\n",
+ "Let us study some examples. The first code here takes a simple\n",
+ "one-dimensional second-order polynomial and we fit it to a\n",
+ "second-order polynomial. Depending on the strength of the added noise,\n",
+ "the various measures like the $R2$ score or the mean-squared error,\n",
+ "the fit becomes better or worse."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "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",
+ "\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",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),3))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x**2\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",
+ "# matrix inversion to find beta\n",
+ "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(beta)\n",
+ "# and then make the prediction\n",
+ "ytilde = X_train @ beta\n",
+ "print(\"Training R2\")\n",
+ "print(R2(y_train,ytilde))\n",
+ "print(\"Training MSE\")\n",
+ "print(MSE(y_train,ytilde))\n",
+ "ypredict = X_test @ beta\n",
+ "print(\"Test R2\")\n",
+ "print(R2(y_test,ypredict))\n",
+ "print(\"Test MSE\")\n",
+ "print(MSE(y_test,ypredict))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Alternatively, you could write your own test-train splitting function as shown here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# equivalently in numpy\n",
+ "def train_test_split_numpy(inputs, labels, train_size, test_size):\n",
+ " n_inputs = len(inputs)\n",
+ " inputs_shuffled = inputs.copy()\n",
+ " labels_shuffled = labels.copy()\n",
+ "\n",
+ " np.random.shuffle(inputs_shuffled)\n",
+ " np.random.shuffle(labels_shuffled)\n",
+ "\n",
+ " train_end = int(n_inputs*train_size)\n",
+ " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n",
+ " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n",
+ "\n",
+ " return X_train, X_test, Y_train, Y_test"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But since **scikit-learn** has its own function for doing this and since\n",
+ "it interfaces easily with **tensorflow** and other libraries, we\n",
+ "normally recommend using the latter functionality.\n",
+ "\n",
+ "\n",
+ "As another example, we apply the training and testing split to \n",
+ "to the above equation of state fitting example\n",
+ "but now splitting the data into a training set and a test set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "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",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\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",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organized into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "X = np.zeros((len(Density),5))\n",
+ "X[:,0] = 1\n",
+ "X[:,1] = Density**(2.0/3.0)\n",
+ "X[:,2] = Density\n",
+ "X[:,3] = Density**(4.0/3.0)\n",
+ "X[:,4] = Density**(5.0/3.0)\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ "# matrix inversion to find beta\n",
+ "beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n",
+ "# and then make the prediction\n",
+ "ytilde = X_train @ beta\n",
+ "print(\"Training R2\")\n",
+ "print(R2(y_train,ytilde))\n",
+ "print(\"Training MSE\")\n",
+ "print(MSE(y_train,ytilde))\n",
+ "ypredict = X_test @ beta\n",
+ "print(\"Test R2\")\n",
+ "print(R2(y_test,ypredict))\n",
+ "print(\"Test MSE\")\n",
+ "print(MSE(y_test,ypredict))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The Boston housing data example\n",
+ "\n",
+ "The Boston housing \n",
+ "data set was originally a part of UCI Machine Learning Repository\n",
+ "and has been removed now. The data set is now included in **Scikit-Learn**'s \n",
+ "library. There are 506 samples and 13 feature (predictor) variables\n",
+ "in this data set. The objective is to predict the value of prices of\n",
+ "the house using the features (predictors) listed here.\n",
+ "\n",
+ "The features/predictors are\n",
+ "1. CRIM: Per capita crime rate by town\n",
+ "\n",
+ "2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n",
+ "\n",
+ "3. INDUS: Proportion of non-retail business acres per town\n",
+ "\n",
+ "4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n",
+ "\n",
+ "5. NOX: Nitric oxide concentration (parts per 10 million)\n",
+ "\n",
+ "6. RM: Average number of rooms per dwelling\n",
+ "\n",
+ "7. AGE: Proportion of owner-occupied units built prior to 1940\n",
+ "\n",
+ "8. DIS: Weighted distances to five Boston employment centers\n",
+ "\n",
+ "9. RAD: Index of accessibility to radial highways\n",
+ "\n",
+ "10. TAX: Full-value property tax rate per USD10000\n",
+ "\n",
+ "11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n",
+ "\n",
+ "12. LSTAT: Percentage of lower status of the population\n",
+ "\n",
+ "13. MEDV: Median value of owner-occupied homes in USD 1000s\n",
+ "\n",
+ "## Housing data, the code\n",
+ "We start by importing the libraries"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt \n",
+ "\n",
+ "import pandas as pd \n",
+ "import seaborn as sns"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and load the Boston Housing DataSet from **Scikit-Learn**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.datasets import load_boston\n",
+ "\n",
+ "boston_dataset = load_boston()\n",
+ "\n",
+ "# boston_dataset is a dictionary\n",
+ "# let's check what it contains\n",
+ "boston_dataset.keys()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then we invoke Pandas"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n",
+ "boston.head()\n",
+ "boston['MEDV'] = boston_dataset.target"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and preprocess the data"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# check for missing values in all the columns\n",
+ "boston.isnull().sum()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can then visualize the data"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# set the size of the figure\n",
+ "sns.set(rc={'figure.figsize':(11.7,8.27)})\n",
+ "\n",
+ "# plot a histogram showing the distribution of the target values\n",
+ "sns.distplot(boston['MEDV'], bins=30)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is now useful to look at the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# compute the pair wise correlation for all columns \n",
+ "correlation_matrix = boston.corr().round(2)\n",
+ "# use the heatmap function from seaborn to plot the correlation matrix\n",
+ "# annot = True to print the values inside the square\n",
+ "sns.heatmap(data=correlation_matrix, annot=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "From the above coorelation plot we can see that **MEDV** is strongly correlated to **LSTAT** and **RM**. We see also that **RAD** and **TAX** are stronly correlated, but we don't include this in our features together to avoid multi-colinearity"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "plt.figure(figsize=(20, 5))\n",
+ "\n",
+ "features = ['LSTAT', 'RM']\n",
+ "target = boston['MEDV']\n",
+ "\n",
+ "for i, col in enumerate(features):\n",
+ " plt.subplot(1, len(features) , i+1)\n",
+ " x = boston[col]\n",
+ " y = target\n",
+ " plt.scatter(x, y, marker='o')\n",
+ " plt.title(col)\n",
+ " plt.xlabel(col)\n",
+ " plt.ylabel('MEDV')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we start training our model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n",
+ "Y = boston['MEDV']"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We split the data into training and test sets"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.model_selection import train_test_split\n",
+ "\n",
+ "# splits the training and test data set in 80% : 20%\n",
+ "# assign random_state to any value.This ensures consistency.\n",
+ "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "print(Y_train.shape)\n",
+ "print(Y_test.shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then we use the linear regression functionality from **Scikit-Learn**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.metrics import mean_squared_error, r2_score\n",
+ "\n",
+ "lin_model = LinearRegression()\n",
+ "lin_model.fit(X_train, Y_train)\n",
+ "\n",
+ "# model evaluation for training set\n",
+ "\n",
+ "y_train_predict = lin_model.predict(X_train)\n",
+ "rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n",
+ "r2 = r2_score(Y_train, y_train_predict)\n",
+ "\n",
+ "print(\"The model performance for training set\")\n",
+ "print(\"--------------------------------------\")\n",
+ "print('RMSE is {}'.format(rmse))\n",
+ "print('R2 score is {}'.format(r2))\n",
+ "print(\"\\n\")\n",
+ "\n",
+ "# model evaluation for testing set\n",
+ "\n",
+ "y_test_predict = lin_model.predict(X_test)\n",
+ "# root mean square error of the model\n",
+ "rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n",
+ "\n",
+ "# r-squared score of the model\n",
+ "r2 = r2_score(Y_test, y_test_predict)\n",
+ "\n",
+ "print(\"The model performance for testing set\")\n",
+ "print(\"--------------------------------------\")\n",
+ "print('RMSE is {}'.format(rmse))\n",
+ "print('R2 score is {}'.format(r2))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# plotting the y_test vs y_pred\n",
+ "# ideally should have been a straight line\n",
+ "plt.scatter(Y_test, y_test_predict)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Reducing the number of degrees of freedom, overarching view\n",
+ "\n",
+ "Many Machine Learning problems involve thousands or even millions of\n",
+ "features for each training instance. Not only does this make training\n",
+ "extremely slow, it can also make it much harder to find a good\n",
+ "solution, as we will see. This problem is often referred to as the\n",
+ "curse of dimensionality. Fortunately, in real-world problems, it is\n",
+ "often possible to reduce the number of features considerably, turning\n",
+ "an intractable problem into a tractable one.\n",
+ "\n",
+ "Later we will discuss some of the most popular dimensionality reduction\n",
+ "techniques: the principal component analysis (PCA), Kernel PCA, and\n",
+ "Locally Linear Embedding (LLE). \n",
+ "\n",
+ "\n",
+ "Principal component analysis and its various variants deal with the\n",
+ "problem of fitting a low-dimensional [affine\n",
+ "subspace](https://en.wikipedia.org/wiki/Affine_space) to a set of of\n",
+ "data points in a high-dimensional space. With its family of methods it\n",
+ "is one of the most used tools in data modeling, compression and\n",
+ "visualization.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Before we proceed however, we will discuss how to preprocess our\n",
+ "data. Till now and in connection with our previous examples we have\n",
+ "not met so many cases where we are too sensitive to the scaling of 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",
+ "For data sets gathered for real world applications, it is rather normal that\n",
+ "different features have very different units and\n",
+ "numerical scales. For example, a data set detailing health habits may include\n",
+ "features such as **age** in the range $0-80$, and **caloric intake** of order $2000$.\n",
+ "Many machine learning methods sensitive to the scales of the features and may perform poorly if they\n",
+ "are very different scales. Therefore, it is typical to scale\n",
+ "the features in a way to avoid such outlier values.\n",
+ "\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",
+ "Many features are often scaled using standardization to improve\n",
+ "performance. In **Scikit-Learn** this is given by the **StandardScaler**\n",
+ "function as discussed above. It is easy however to write your own.\n",
+ "Mathematically, this involves subtracting the mean and divide by the\n",
+ "standard deviation over the data set, for each feature:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "x_j^{(i)} \\rightarrow \\frac{x_j^{(i)} - \\overline{x}_j}{\\sigma(x_j)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\overline{x}_j$ and $\\sigma(x_j)$ are the mean and standard\n",
+ "deviation, respectively, of the feature $x_j$. This ensures that each\n",
+ "feature has zero mean and unit standard deviation. For data sets\n",
+ "where we do not have the standard deviation or don't wish to calculate\n",
+ "it, it is then common to simply set it to one.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us consider the following vanilla example where we use both\n",
+ "**Scikit-Learn** and write our own function as well. We produce a\n",
+ "simple test design matrix with random numbers. Each column could then\n",
+ "represent a specific feature whose mean value is subracted."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import sklearn.linear_model as skl\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "from IPython.display import display\n",
+ "np.random.seed(100)\n",
+ "# setting up a 10 x 5 matrix\n",
+ "rows = 10\n",
+ "cols = 5\n",
+ "X = np.random.randn(rows,cols)\n",
+ "XPandas = pd.DataFrame(X)\n",
+ "display(XPandas)\n",
+ "print(XPandas.mean())\n",
+ "print(XPandas.std())\n",
+ "XPandas = (XPandas -XPandas.mean())\n",
+ "display(XPandas)\n",
+ "# This option does not include the standard deviation\n",
+ "scaler = StandardScaler(with_std=False)\n",
+ "scaler.fit(X)\n",
+ "Xscaled = scaler.transform(X)\n",
+ "display(XPandas-Xscaled)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Another commonly used scaling method is min-max scaling. This is very\n",
+ "useful for when we want the features to lie in a certain interval. To\n",
+ "scale the feature $x_j$ to the interval $[a, b]$, we can apply the\n",
+ "transformation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "x_j^{(i)} \\rightarrow (b-a)\\frac{x_j^{(i)} - \\min(x_j)}{\\max(x_j) - \\min(x_j)} - a\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\min(x_j)$ and $\\max(x_j)$ return the minimum and maximum value of $x_j$ over the data set, respectively.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Testing the Means Squared Error as function of Complexity\n",
+ "\n",
+ "\n",
+ "Before we proceed with a more detailed analysis of the so-called\n",
+ "Bias-Variance tradeoff, we present here an example of the relation\n",
+ "between model complexity and the mean squared error for the triaining\n",
+ "data and the test data.\n",
+ "\n",
+ "The results here tell us clearly that for the data not included in the\n",
+ "training, there is an optimal model as function of the complexity of\n",
+ "ourmodel (here in terms of the polynomial degree of the model).\n",
+ "\n",
+ "The results here will vary as function of model complexity and the amount od data used for training. \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": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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 = 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)\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",
+ "\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " clf = model.fit(x_train,y_train)\n",
+ " y_fit = clf.predict(x_train)\n",
+ " y_pred = clf.predict(x_test) \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": [
+ "## Exercises\n",
+ "\n",
+ "### Exercise: Setting up various Python environments\n",
+ "\n",
+ "The first exercise here is of a mere technical art. We want you to have \n",
+ "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n",
+ "\n",
+ "* Install various Python packages\n",
+ "\n",
+ "We will make extensive use of Python as programming language and its\n",
+ "myriad of available libraries. You will find\n",
+ "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n",
+ "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n",
+ "visualizing your data. You can also use compiled languages like C++,\n",
+ "Rust, Fortran etc if you prefer. The focus in these lectures will be\n",
+ "on Python.\n",
+ "\n",
+ "If you have Python installed (we recommend Python3) and you feel\n",
+ "pretty familiar with installing different packages, we recommend that\n",
+ "you install the following Python packages via **pip** as \n",
+ "\n",
+ "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n",
+ "\n",
+ "For **Tensorflow**, we recommend following the instructions in the text of \n",
+ "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n",
+ "\n",
+ "We will come back to **tensorflow** later. \n",
+ "\n",
+ "For Python3, replace **pip** with **pip3**.\n",
+ "\n",
+ "For OSX users we recommend, after having installed Xcode, to\n",
+ "install **brew**. Brew allows for a seamless installation of additional\n",
+ "software via for example \n",
+ "\n",
+ "1. brew install python3\n",
+ "\n",
+ "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n",
+ "you can use **pip** as well and simply install Python as \n",
+ "\n",
+ "1. sudo apt-get install python3 (or python for Python2.7)\n",
+ "\n",
+ "If you don't want to perform these operations separately and venture\n",
+ "into the hassle of exploring how to set up dependencies and paths, we\n",
+ "recommend two widely used distrubutions which set up all relevant\n",
+ "dependencies for Python, namely \n",
+ "\n",
+ "* [Anaconda](https://docs.anaconda.com/), \n",
+ "\n",
+ "which is an open source\n",
+ "distribution of the Python and R programming languages for large-scale\n",
+ "data processing, predictive analytics, and scientific computing, that\n",
+ "aims to simplify package management and deployment. Package versions\n",
+ "are managed by the package management system **conda**. \n",
+ "\n",
+ "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n",
+ "\n",
+ "is a Python\n",
+ "distribution for scientific and analytic computing distribution and\n",
+ "analysis environment, available for free and under a commercial\n",
+ "license.\n",
+ "\n",
+ "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Exercise: making your own data and exploring scikit-learn\n",
+ "\n",
+ "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n",
+ "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "x = np.random.rand(100,1)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100,1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n",
+ "\n",
+ "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n",
+ "\n",
+ "3. Using scikit-learn, 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(\\boldsymbol{y},\\boldsymbol{\\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{\\boldsymbol{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(\\boldsymbol{y}, \\tilde{\\boldsymbol{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 $\\boldsymbol{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": [
+ "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n",
+ "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Exercise: 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": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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",
+ "\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": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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",
+ "Write a first code which sets up a design matrix $X$ defined by a\n",
+ "fifth-order polynomial. Scale your data and split it in training and\n",
+ "test data.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Perform an ordinary least squares and compute the means squared error\n",
+ "and the $R2$ factor for the training data and the test data, with and\n",
+ "without scaling.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Add now a model which allows you to make polynomials up to degree\n",
+ "$15$. Perform a standard OLS fitting of the training data and compute\n",
+ "the MSE and $R2$ for the training and test data and plot both test and\n",
+ "training data MSE and $R2$ as functions of the polynomial\n",
+ "degree. Compare what you see with Figure 2.11 of Hastie et al. Comment\n",
+ "your results. For which polynomial degree do you find an optimal MSE\n",
+ "(smallest value)?"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter10.ipynb b/doc/LectureNotes/_build/html/_sources/chapter10.ipynb
new file mode 100644
index 000000000..cc65cfe33
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter10.ipynb
@@ -0,0 +1,2047 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Building a Feed Forward Neural Network\n",
+ "\n",
+ "We are now gong to develop an example based on the MNIST data\n",
+ "base. This is a classification problem and we need to use our\n",
+ "cross-entropy function we discussed in connection with logistic\n",
+ "regression. The cross-entropy defines our cost function for the\n",
+ "classificaton problems with neural networks.\n",
+ "\n",
+ "In binary classification with two classes $(0, 1)$ we define the\n",
+ "logistic/sigmoid function as the probability that a particular input\n",
+ "is in class $0$ or $1$. This is possible because the logistic\n",
+ "function takes any input from the real numbers and inputs a number\n",
+ "between 0 and 1, and can therefore be interpreted as a probability. It\n",
+ "also has other nice properties, such as a derivative that is simple to\n",
+ "calculate.\n",
+ "\n",
+ "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n",
+ "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$\n",
+ "represents our activation values $z$. We have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) = \\frac{1}{1 + \\exp{(- \\hat{x}})} ,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(y = 1 \\mid \\hat{x}, \\hat{\\theta}) = 1 - P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) ,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $y \\in \\{0, 1\\}$ and $\\hat{\\theta}$ represents the weights and biases\n",
+ "of our network.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Defining the cost function\n",
+ "\n",
+ "Our cost function is given as (see the Logistic regression lectures)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\hat{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\hat{\\theta}) = - \\sum_{i=1}^n\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}) .\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n",
+ "for each point in the dataset $\\mathcal{L}_i(\\hat{\\theta})$. \n",
+ "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n",
+ "than maximizing a negative number. \n",
+ "\n",
+ "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n",
+ "\n",
+ "$y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n",
+ "\n",
+ "\n",
+ "$y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n",
+ "\n",
+ "\n",
+ "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$).. \n",
+ "\n",
+ "If $\\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n",
+ "output vector $\\hat{y}_i$. \n",
+ "The probability of $\\hat{x}_i$ being in class $c$ will be given by the softmax function:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(y_{ic} = 1 \\mid \\hat{x}_i, \\hat{\\theta}) = \\frac{\\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_c)}}\n",
+ "{\\sum_{c'=0}^{C-1} \\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_{c'})}} ,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which reduces to the logistic function in the binary case. \n",
+ "The likelihood of this $C$-class classifier\n",
+ "is now given as:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(\\mathcal{D} \\mid \\hat{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Again we take the negative log-likelihood to define our cost function:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\hat{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\hat{\\theta})}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See the logistic regression lectures for a full definition of the cost function.\n",
+ "\n",
+ "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!\n",
+ "\n",
+ "\n",
+ "### Example: binary classification problem\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we had defined the logistic (sigmoid) function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "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)}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(y_i =0\\vert x_i,\\hat{\\beta})=1-p(y_i =1\\vert x_i,\\hat{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The parameters $\\hat{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n",
+ "\n",
+ "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$. \n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n",
+ "Our cost function at the final layer $l=L$ is now"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\hat{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\mathcal{C}(\\hat{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In case we use another activation function than the logistic one, we need to evaluate other derivatives. \n",
+ "\n",
+ "\n",
+ "\n",
+ "### The Softmax function\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n",
+ "\\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}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the Softmax function we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Its derivative with respect to $z_j^l$ gives"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in case of the simply binary model reduces to having $i=j$. \n",
+ "\n",
+ "\n",
+ "## Developing a code for doing neural networks with back propagation\n",
+ "\n",
+ "\n",
+ "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n",
+ "\n",
+ "1. Collect and pre-process data \n",
+ "\n",
+ "2. Define model and architecture \n",
+ "\n",
+ "3. Choose cost function and optimizer \n",
+ "\n",
+ "4. Train the model \n",
+ "\n",
+ "5. Evaluate model performance on test data \n",
+ "\n",
+ "6. Adjust hyperparameters (if necessary, network architecture)\n",
+ "\n",
+ "### Collect and pre-process data\n",
+ "\n",
+ "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n",
+ "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n",
+ "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n",
+ "of handwritten digits that is commonly used for training various image processing systems. \n",
+ "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n",
+ "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. \n",
+ "\n",
+ "To feed data into a feed-forward neural network we need to represent\n",
+ "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n",
+ "row represents an *input*, in this case a handwritten digit, and\n",
+ "each column represents a *feature*, in this case a pixel. The\n",
+ "correct answers, also known as *labels* or *targets* are\n",
+ "represented as a 1D array of integers \n",
+ "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n",
+ "\n",
+ "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n",
+ "measurements of height (in m) \n",
+ "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n",
+ "\n",
+ "$$ X = \\begin{bmatrix}\n",
+ "1.85 & 81\\\\\n",
+ "1.71 & 65\\\\\n",
+ "1.95 & 103\\\\\n",
+ "1.55 & 42\\\\\n",
+ "1.63 & 56\n",
+ "\\end{bmatrix} ,$$ \n",
+ "\n",
+ "and the targets would be: \n",
+ "\n",
+ "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n",
+ "\n",
+ "Since each input image is a 2D matrix, we need to flatten the image\n",
+ "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n",
+ "design/feature matrix. This means we lose all spatial information in the\n",
+ "image, such as locality and translational invariance. More complicated\n",
+ "architectures such as Convolutional Neural Networks can take advantage\n",
+ "of such information, and are most commonly applied when analyzing\n",
+ "images."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "# import necessary packages\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn import datasets\n",
+ "\n",
+ "\n",
+ "# ensure the same random numbers appear every time\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "# display images in notebook\n",
+ "%matplotlib inline\n",
+ "plt.rcParams['figure.figsize'] = (12,12)\n",
+ "\n",
+ "\n",
+ "# download MNIST dataset\n",
+ "digits = datasets.load_digits()\n",
+ "\n",
+ "# define inputs and labels\n",
+ "inputs = digits.images\n",
+ "labels = digits.target\n",
+ "\n",
+ "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n",
+ "print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
+ "\n",
+ "\n",
+ "# flatten the image\n",
+ "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n",
+ "n_inputs = len(inputs)\n",
+ "inputs = inputs.reshape(n_inputs, -1)\n",
+ "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n",
+ "\n",
+ "\n",
+ "# choose some random images to display\n",
+ "indices = np.arange(n_inputs)\n",
+ "random_indices = np.random.choice(indices, size=5)\n",
+ "\n",
+ "for i, image in enumerate(digits.images[random_indices]):\n",
+ " plt.subplot(1, 5, i+1)\n",
+ " plt.axis('off')\n",
+ " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
+ " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Train and test datasets\n",
+ "\n",
+ "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n",
+ "\n",
+ "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n",
+ "\n",
+ "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n",
+ "no bias in the sampling. \n",
+ "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n",
+ "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\n",
+ "collected from 12.00 to 24.00."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.model_selection import train_test_split\n",
+ "\n",
+ "# one-liner from scikit-learn library\n",
+ "train_size = 0.8\n",
+ "test_size = 1 - train_size\n",
+ "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
+ " test_size=test_size)\n",
+ "\n",
+ "# equivalently in numpy\n",
+ "def train_test_split_numpy(inputs, labels, train_size, test_size):\n",
+ " n_inputs = len(inputs)\n",
+ " inputs_shuffled = inputs.copy()\n",
+ " labels_shuffled = labels.copy()\n",
+ " \n",
+ " np.random.shuffle(inputs_shuffled)\n",
+ " np.random.shuffle(labels_shuffled)\n",
+ " \n",
+ " train_end = int(n_inputs*train_size)\n",
+ " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n",
+ " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n",
+ " \n",
+ " return X_train, X_test, Y_train, Y_test\n",
+ "\n",
+ "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n",
+ "\n",
+ "print(\"Number of training images: \" + str(len(X_train)))\n",
+ "print(\"Number of test images: \" + str(len(X_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Define model and architecture\n",
+ "\n",
+ "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 \n",
+ "\n",
+ "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n",
+ "\n",
+ "$$ y = f(z) ,$$\n",
+ "\n",
+ "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n",
+ "and $w_i$ is the weight to input $i$. \n",
+ "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n",
+ "\n",
+ "The simplest activation function for a neuron is the *Heaviside* function:\n",
+ "\n",
+ "$$ f(z) = \n",
+ "\\begin{cases}\n",
+ "1, & z > 0\\\\\n",
+ "0, & \\text{otherwise}\n",
+ "\\end{cases}\n",
+ "$$\n",
+ "\n",
+ "A feed-forward neural network with this activation is known as a *perceptron*. \n",
+ "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n",
+ "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n",
+ "and we call these architectures *multiclass perceptrons*. \n",
+ "\n",
+ "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n",
+ "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n",
+ "\n",
+ "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n",
+ "We will be using the sigmoid function $\\sigma(x)$: \n",
+ "\n",
+ "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n",
+ "\n",
+ "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.\n",
+ "\n",
+ "### Layers\n",
+ "\n",
+ "* Input \n",
+ "\n",
+ "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n",
+ "\n",
+ "* Hidden layer\n",
+ "\n",
+ "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n",
+ "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n",
+ "\n",
+ "* Output\n",
+ "\n",
+ "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n",
+ "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. \n",
+ "\n",
+ "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. \n",
+ "\n",
+ "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: \n",
+ "\n",
+ "$$ P(\\text{class $j$} \\mid \\text{input $\\hat{a}$}) = \\frac{\\exp{(\\hat{a}^T \\hat{w}_j)}}\n",
+ "{\\sum_{c=0}^{9} \\exp{(\\hat{a}^T \\hat{w}_c)}} ,$$ \n",
+ "\n",
+ "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. \n",
+ "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n",
+ "The exponent is just the weighted sum of inputs as before: \n",
+ "\n",
+ "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n",
+ "\n",
+ "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n",
+ "weights to the output layer.\n",
+ "\n",
+ "\n",
+ "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n",
+ "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n",
+ "\n",
+ "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n",
+ "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$: \n",
+ "\n",
+ "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n",
+ "\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# building our neural network\n",
+ "\n",
+ "n_inputs, n_features = X_train.shape\n",
+ "n_hidden_neurons = 50\n",
+ "n_categories = 10\n",
+ "\n",
+ "# we make the weights normally distributed using numpy.random.randn\n",
+ "\n",
+ "# weights and bias in the hidden layer\n",
+ "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n",
+ "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n",
+ "\n",
+ "# weights and bias in the output layer\n",
+ "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n",
+ "output_bias = np.zeros(n_categories) + 0.01"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Feed-forward pass\n",
+ "\n",
+ "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n",
+ "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n",
+ "\n",
+ "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n",
+ "\n",
+ "this is then passed through our activation function \n",
+ "\n",
+ "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n",
+ "\n",
+ "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n",
+ "\n",
+ "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n",
+ "\n",
+ "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n",
+ "\n",
+ "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n",
+ "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$ \n",
+ "\n",
+ "\n",
+ "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n",
+ "layer have the dimensions \n",
+ "$W_{hidden} = (n_{features}, n_{hidden})$,\n",
+ "we can easily feed the network all our training data in one go by taking the matrix product \n",
+ "\n",
+ "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n",
+ "\n",
+ "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n",
+ "for each input image and each hidden neuron. \n",
+ "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n",
+ "\n",
+ "$$ \\hat{z}^{l} = \\hat{X} \\hat{W}^{l} + \\hat{b}^{l} ,$$\n",
+ "\n",
+ "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n",
+ "This is then passed through the activation: \n",
+ "\n",
+ "$$ \\hat{a}^{l} = f(\\hat{z}^l) .$$ \n",
+ "\n",
+ "This is fed to the output layer: \n",
+ "\n",
+ "$$ \\hat{z}^{L} = \\hat{a}^{L} \\hat{W}^{L} + \\hat{b}^{L} .$$\n",
+ "\n",
+ "Finally we receive our output values for each image and each category by passing it through the softmax function: \n",
+ "\n",
+ "$$ output = softmax (\\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# setup the feed-forward pass, subscript h = hidden layer\n",
+ "\n",
+ "def sigmoid(x):\n",
+ " return 1/(1 + np.exp(-x))\n",
+ "\n",
+ "def feed_forward(X):\n",
+ " # weighted sum of inputs to the hidden layer\n",
+ " z_h = np.matmul(X, hidden_weights) + hidden_bias\n",
+ " # activation in the hidden layer\n",
+ " a_h = sigmoid(z_h)\n",
+ " \n",
+ " # weighted sum of inputs to the output layer\n",
+ " z_o = np.matmul(a_h, output_weights) + output_bias\n",
+ " # softmax output\n",
+ " # axis 0 holds each input and axis 1 the probabilities of each category\n",
+ " exp_term = np.exp(z_o)\n",
+ " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n",
+ " \n",
+ " return probabilities\n",
+ "\n",
+ "probabilities = feed_forward(X_train)\n",
+ "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n",
+ "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n",
+ "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n",
+ "print()\n",
+ "\n",
+ "# we obtain a prediction by taking the class with the highest likelihood\n",
+ "def predict(X):\n",
+ " probabilities = feed_forward(X)\n",
+ " return np.argmax(probabilities, axis=1)\n",
+ "\n",
+ "predictions = predict(X_train)\n",
+ "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n",
+ "print(\"prediction for image 0: \" + str(predictions[0]))\n",
+ "print(\"correct label for image 0: \" + str(Y_train[0]))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Choose cost function and optimizer\n",
+ "\n",
+ "To measure how well our neural network is doing we need to introduce a cost function. \n",
+ "We will call the function that gives the error of a single sample output the *loss* function, and the function\n",
+ "that gives the total error of our network across all samples the *cost* function.\n",
+ "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n",
+ "\n",
+ "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n",
+ "\n",
+ "$$ y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n",
+ "\n",
+ "\n",
+ "$$ y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n",
+ "\n",
+ "\n",
+ "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n",
+ "\n",
+ "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n",
+ "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\hat{x}_i$ in the dataset.\n",
+ "\n",
+ "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n",
+ "probability of the correct category $c'$ \n",
+ "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n",
+ "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. \n",
+ "\n",
+ "\n",
+ "\n",
+ "### Optimizing the cost function\n",
+ "\n",
+ "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\n",
+ "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. \n",
+ "Each parameter $\\theta$ is iteratively adjusted according to the rule \n",
+ "\n",
+ "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n",
+ "\n",
+ "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n",
+ "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n",
+ "\n",
+ "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n",
+ "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n",
+ "on a subset of the data called a *minibatch*. \n",
+ "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n",
+ "is $N/M$. \n",
+ "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n",
+ "\n",
+ "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n",
+ "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n",
+ "\n",
+ "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n",
+ "\n",
+ "This has two important benefits: \n",
+ "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n",
+ "\n",
+ "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n",
+ "\n",
+ "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).\n",
+ "\n",
+ "\n",
+ "### Regularization\n",
+ "\n",
+ "It is common to add an extra term to the cost function, proportional\n",
+ "to the size of the weights. This is equivalent to constraining the\n",
+ "size of the weights, so that they do not grow out of control.\n",
+ "Constraining the size of the weights means that the weights cannot\n",
+ "grow arbitrarily large to fit the training data, and in this way\n",
+ "reduces *overfitting*.\n",
+ "\n",
+ "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n",
+ "\n",
+ "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n",
+ "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n",
+ "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n",
+ "\n",
+ "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n",
+ "\n",
+ "\n",
+ "In order to train the model, we need to calculate the derivative of\n",
+ "the cost function with respect to every bias and weight in the\n",
+ "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n",
+ "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n",
+ "layer ($+1$ for the bias), and the gradient must be calculated for\n",
+ "every parameter. We use the *backpropagation* algorithm discussed\n",
+ "above. This is a clever use of the chain rule that allows us to\n",
+ "calculate the gradient efficently. \n",
+ "\n",
+ "\n",
+ "### Matrix multiplication\n",
+ "\n",
+ "To more efficently train our network these equations are implemented using matrix operations. \n",
+ "The error in the output layer is calculated simply as, with $\\hat{t}$ being our targets, \n",
+ "\n",
+ "$$ \\delta_L = \\hat{t} - \\hat{y} = (n_{inputs}, n_{categories}) .$$ \n",
+ "\n",
+ "The gradient for the output weights is calculated as \n",
+ "\n",
+ "$$ \\nabla W_{L} = \\hat{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n",
+ "\n",
+ "where $\\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n",
+ "Since we are going backwards we have to transpose the activation matrix. \n",
+ "\n",
+ "The gradient with respect to the output bias is then \n",
+ "\n",
+ "$$ \\nabla \\hat{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n",
+ "\n",
+ "The error in the hidden layer is \n",
+ "\n",
+ "$$ \\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}) ,$$ \n",
+ "\n",
+ "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n",
+ "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n",
+ "the *Hadamard product*, meaning element-wise multiplication. \n",
+ "\n",
+ "This again gives us the gradients in the hidden layer: \n",
+ "\n",
+ "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n",
+ "\n",
+ "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# to categorical turns our integer vector into a onehot representation\n",
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "# one-hot in numpy\n",
+ "def to_categorical_numpy(integer_vector):\n",
+ " n_inputs = len(integer_vector)\n",
+ " n_categories = np.max(integer_vector) + 1\n",
+ " onehot_vector = np.zeros((n_inputs, n_categories))\n",
+ " onehot_vector[range(n_inputs), integer_vector] = 1\n",
+ " \n",
+ " return onehot_vector\n",
+ "\n",
+ "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n",
+ "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n",
+ "\n",
+ "def feed_forward_train(X):\n",
+ " # weighted sum of inputs to the hidden layer\n",
+ " z_h = np.matmul(X, hidden_weights) + hidden_bias\n",
+ " # activation in the hidden layer\n",
+ " a_h = sigmoid(z_h)\n",
+ " \n",
+ " # weighted sum of inputs to the output layer\n",
+ " z_o = np.matmul(a_h, output_weights) + output_bias\n",
+ " # softmax output\n",
+ " # axis 0 holds each input and axis 1 the probabilities of each category\n",
+ " exp_term = np.exp(z_o)\n",
+ " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n",
+ " \n",
+ " # for backpropagation need activations in hidden and output layers\n",
+ " return a_h, probabilities\n",
+ "\n",
+ "def backpropagation(X, Y):\n",
+ " a_h, probabilities = feed_forward_train(X)\n",
+ " \n",
+ " # error in the output layer\n",
+ " error_output = probabilities - Y\n",
+ " # error in the hidden layer\n",
+ " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n",
+ " \n",
+ " # gradients for the output layer\n",
+ " output_weights_gradient = np.matmul(a_h.T, error_output)\n",
+ " output_bias_gradient = np.sum(error_output, axis=0)\n",
+ " \n",
+ " # gradient for the hidden layer\n",
+ " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n",
+ " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n",
+ "\n",
+ " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n",
+ "\n",
+ "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n",
+ "\n",
+ "eta = 0.01\n",
+ "lmbd = 0.01\n",
+ "for i in range(1000):\n",
+ " # calculate gradients\n",
+ " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n",
+ " \n",
+ " # regularization term gradients\n",
+ " dWo += lmbd * output_weights\n",
+ " dWh += lmbd * hidden_weights\n",
+ " \n",
+ " # update weights and biases\n",
+ " output_weights -= eta * dWo\n",
+ " output_bias -= eta * dBo\n",
+ " hidden_weights -= eta * dWh\n",
+ " hidden_bias -= eta * dBh\n",
+ "\n",
+ "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Improving performance\n",
+ "\n",
+ "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. \n",
+ "In order to obtain a network that does something useful, we will have to do a bit more work. \n",
+ "\n",
+ "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}$. \n",
+ "\n",
+ "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\n",
+ "going through the entire dataset ($n/M$ batches) an *epoch*.\n",
+ "\n",
+ "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n",
+ "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/). \n",
+ "\n",
+ "\n",
+ "It is very natural to think of the network as an object, with specific instances of the network\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "class NeuralNetwork:\n",
+ " def __init__(\n",
+ " self,\n",
+ " X_data,\n",
+ " Y_data,\n",
+ " n_hidden_neurons=50,\n",
+ " n_categories=10,\n",
+ " epochs=10,\n",
+ " batch_size=100,\n",
+ " eta=0.1,\n",
+ " lmbd=0.0):\n",
+ "\n",
+ " self.X_data_full = X_data\n",
+ " self.Y_data_full = Y_data\n",
+ "\n",
+ " self.n_inputs = X_data.shape[0]\n",
+ " self.n_features = X_data.shape[1]\n",
+ " self.n_hidden_neurons = n_hidden_neurons\n",
+ " self.n_categories = n_categories\n",
+ "\n",
+ " self.epochs = epochs\n",
+ " self.batch_size = batch_size\n",
+ " self.iterations = self.n_inputs // self.batch_size\n",
+ " self.eta = eta\n",
+ " self.lmbd = lmbd\n",
+ "\n",
+ " self.create_biases_and_weights()\n",
+ "\n",
+ " def create_biases_and_weights(self):\n",
+ " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n",
+ " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n",
+ "\n",
+ " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n",
+ " self.output_bias = np.zeros(self.n_categories) + 0.01\n",
+ "\n",
+ " def feed_forward(self):\n",
+ " # feed-forward for training\n",
+ " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n",
+ " self.a_h = sigmoid(self.z_h)\n",
+ "\n",
+ " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n",
+ "\n",
+ " exp_term = np.exp(self.z_o)\n",
+ " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n",
+ "\n",
+ " def feed_forward_out(self, X):\n",
+ " # feed-forward for output\n",
+ " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n",
+ " a_h = sigmoid(z_h)\n",
+ "\n",
+ " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n",
+ " \n",
+ " exp_term = np.exp(z_o)\n",
+ " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n",
+ " return probabilities\n",
+ "\n",
+ " def backpropagation(self):\n",
+ " error_output = self.probabilities - self.Y_data\n",
+ " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n",
+ "\n",
+ " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n",
+ " self.output_bias_gradient = np.sum(error_output, axis=0)\n",
+ "\n",
+ " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n",
+ " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n",
+ "\n",
+ " if self.lmbd > 0.0:\n",
+ " self.output_weights_gradient += self.lmbd * self.output_weights\n",
+ " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n",
+ "\n",
+ " self.output_weights -= self.eta * self.output_weights_gradient\n",
+ " self.output_bias -= self.eta * self.output_bias_gradient\n",
+ " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n",
+ " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n",
+ "\n",
+ " def predict(self, X):\n",
+ " probabilities = self.feed_forward_out(X)\n",
+ " return np.argmax(probabilities, axis=1)\n",
+ "\n",
+ " def predict_probabilities(self, X):\n",
+ " probabilities = self.feed_forward_out(X)\n",
+ " return probabilities\n",
+ "\n",
+ " def train(self):\n",
+ " data_indices = np.arange(self.n_inputs)\n",
+ "\n",
+ " for i in range(self.epochs):\n",
+ " for j in range(self.iterations):\n",
+ " # pick datapoints with replacement\n",
+ " chosen_datapoints = np.random.choice(\n",
+ " data_indices, size=self.batch_size, replace=False\n",
+ " )\n",
+ "\n",
+ " # minibatch training data\n",
+ " self.X_data = self.X_data_full[chosen_datapoints]\n",
+ " self.Y_data = self.Y_data_full[chosen_datapoints]\n",
+ "\n",
+ " self.feed_forward()\n",
+ " self.backpropagation()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Evaluate model performance on test data\n",
+ "\n",
+ "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. \n",
+ "We measure the performance of the network using the *accuracy* score. \n",
+ "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$. \n",
+ "\n",
+ "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\hat{y}_i = y_i)}{n} ,$$ \n",
+ "\n",
+ "where $I$ is the indicator function, $1$ if $\\hat{y}_i = y_i$ and $0$ otherwise."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "epochs = 100\n",
+ "batch_size = 100\n",
+ "\n",
+ "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n",
+ " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n",
+ "dnn.train()\n",
+ "test_predict = dnn.predict(X_test)\n",
+ "\n",
+ "# accuracy score from scikit library\n",
+ "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n",
+ "\n",
+ "# equivalent in numpy\n",
+ "def accuracy_score_numpy(Y_test, Y_pred):\n",
+ " return np.sum(Y_test == Y_pred) / len(Y_test)\n",
+ "\n",
+ "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Adjust hyperparameters\n",
+ "\n",
+ "We now perform a grid search to find the optimal hyperparameters for the network. \n",
+ "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "eta_vals = np.logspace(-5, 1, 7)\n",
+ "lmbd_vals = np.logspace(-5, 1, 7)\n",
+ "# store the models for later use\n",
+ "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
+ "\n",
+ "# grid search\n",
+ "for i, eta in enumerate(eta_vals):\n",
+ " for j, lmbd in enumerate(lmbd_vals):\n",
+ " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n",
+ " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n",
+ " dnn.train()\n",
+ " \n",
+ " DNN_numpy[i][j] = dnn\n",
+ " \n",
+ " test_predict = dnn.predict(X_test)\n",
+ " \n",
+ " print(\"Learning rate = \", eta)\n",
+ " print(\"Lambda = \", lmbd)\n",
+ " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualization"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# visual representation of grid search\n",
+ "# uses seaborn heatmap, you can also do this with matplotlib imshow\n",
+ "import seaborn as sns\n",
+ "\n",
+ "sns.set()\n",
+ "\n",
+ "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "\n",
+ "for i in range(len(eta_vals)):\n",
+ " for j in range(len(lmbd_vals)):\n",
+ " dnn = DNN_numpy[i][j]\n",
+ " \n",
+ " train_pred = dnn.predict(X_train) \n",
+ " test_pred = dnn.predict(X_test)\n",
+ "\n",
+ " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n",
+ " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n",
+ "\n",
+ " \n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Training Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()\n",
+ "\n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Test Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## scikit-learn implementation\n",
+ "\n",
+ "**scikit-learn** focuses more\n",
+ "on traditional machine learning methods, such as regression,\n",
+ "clustering, decision trees, etc. As such, it has only two types of\n",
+ "neural networks: Multi Layer Perceptron outputting continuous values,\n",
+ "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n",
+ "*MLPClassifier*. We will see how simple it is to use these classes.\n",
+ "\n",
+ "**scikit-learn** implements a few improvements from our neural network,\n",
+ "such as early stopping, a varying learning rate, different\n",
+ "optimization methods, etc. We would therefore expect a better\n",
+ "performance overall."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.neural_network import MLPClassifier\n",
+ "# store models for later use\n",
+ "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
+ "\n",
+ "for i, eta in enumerate(eta_vals):\n",
+ " for j, lmbd in enumerate(lmbd_vals):\n",
+ " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
+ " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
+ " dnn.fit(X_train, Y_train)\n",
+ " \n",
+ " DNN_scikit[i][j] = dnn\n",
+ " \n",
+ " print(\"Learning rate = \", eta)\n",
+ " print(\"Lambda = \", lmbd)\n",
+ " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualization"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# optional\n",
+ "# visual representation of grid search\n",
+ "# uses seaborn heatmap, could probably do this in matplotlib\n",
+ "import seaborn as sns\n",
+ "\n",
+ "sns.set()\n",
+ "\n",
+ "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "\n",
+ "for i in range(len(eta_vals)):\n",
+ " for j in range(len(lmbd_vals)):\n",
+ " dnn = DNN_scikit[i][j]\n",
+ " \n",
+ " train_pred = dnn.predict(X_train) \n",
+ " test_pred = dnn.predict(X_test)\n",
+ "\n",
+ " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n",
+ " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n",
+ "\n",
+ " \n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Training Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()\n",
+ "\n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Test Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building neural networks in Tensorflow and Keras\n",
+ "\n",
+ "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n",
+ "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n",
+ "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n",
+ "\n",
+ "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n",
+ "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n",
+ "NumPy arrays.\n",
+ "\n",
+ "\n",
+ "Tensorflow is an open source library machine learning library\n",
+ "developed by the Google Brain team for internal use. It was released\n",
+ "under the Apache 2.0 open source license in November 9, 2015.\n",
+ "\n",
+ "Tensorflow is a computational framework that allows you to construct\n",
+ "machine learning models at different levels of abstraction, from\n",
+ "high-level, object-oriented APIs like Keras, down to the C++ kernels\n",
+ "that Tensorflow is built upon. The higher levels of abstraction are\n",
+ "simpler to use, but less flexible, and our choice of implementation\n",
+ "should reflect the problems we are trying to solve.\n",
+ "\n",
+ "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n",
+ "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n",
+ "to represent your model, and then create a Tensorflow *session* to run the graph.\n",
+ "\n",
+ "In this guide we will analyze the same data as we did in our NumPy and\n",
+ "scikit-learn tutorial, gathered from the MNIST database of images. We\n",
+ "will give an introduction to the lower level Python Application\n",
+ "Program Interfaces (APIs), and see how we use them to build our graph.\n",
+ "Then we will build (effectively) the same graph in Keras, to see just\n",
+ "how simple solving a machine learning problem can be.\n",
+ "\n",
+ "To install tensorflow on Unix/Linux systems, use pip as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pip3 install tensorflow"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n",
+ "(current release of CPU-only TensorFlow)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "conda create -n tf tensorflow\n",
+ "conda activate tf"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To install the current release of GPU TensorFlow"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "conda create -n tf-gpu tensorflow-gpu\n",
+ "conda activate tf-gpu"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n",
+ "that supports Tensorflow, CTNK and Theano as backends. \n",
+ "If you have Anaconda installed you may run the following command"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "conda install keras"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can look up the [instructions here](https://keras.io/) for more information.\n",
+ "\n",
+ "We will to a large extent use **keras** in this course. \n",
+ "\n",
+ "\n",
+ "Let us look again at the MINST data set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# import necessary packages\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import tensorflow as tf\n",
+ "from sklearn import datasets\n",
+ "\n",
+ "\n",
+ "# ensure the same random numbers appear every time\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "# display images in notebook\n",
+ "%matplotlib inline\n",
+ "plt.rcParams['figure.figsize'] = (12,12)\n",
+ "\n",
+ "\n",
+ "# download MNIST dataset\n",
+ "digits = datasets.load_digits()\n",
+ "\n",
+ "# define inputs and labels\n",
+ "inputs = digits.images\n",
+ "labels = digits.target\n",
+ "\n",
+ "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n",
+ "print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
+ "\n",
+ "\n",
+ "# flatten the image\n",
+ "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n",
+ "n_inputs = len(inputs)\n",
+ "inputs = inputs.reshape(n_inputs, -1)\n",
+ "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n",
+ "\n",
+ "\n",
+ "# choose some random images to display\n",
+ "indices = np.arange(n_inputs)\n",
+ "random_indices = np.random.choice(indices, size=5)\n",
+ "\n",
+ "for i, image in enumerate(digits.images[random_indices]):\n",
+ " plt.subplot(1, 5, i+1)\n",
+ " plt.axis('off')\n",
+ " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
+ " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
+ "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
+ "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
+ "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
+ "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
+ "\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "\n",
+ "# one-hot representation of labels\n",
+ "labels = to_categorical(labels)\n",
+ "\n",
+ "# split into train and test data\n",
+ "train_size = 0.8\n",
+ "test_size = 1 - train_size\n",
+ "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
+ " test_size=test_size)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "epochs = 100\n",
+ "batch_size = 100\n",
+ "n_neurons_layer1 = 100\n",
+ "n_neurons_layer2 = 50\n",
+ "n_categories = 10\n",
+ "eta_vals = np.logspace(-5, 1, 7)\n",
+ "lmbd_vals = np.logspace(-5, 1, 7)\n",
+ "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n",
+ " model = Sequential()\n",
+ " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(Dense(n_categories, activation='softmax'))\n",
+ " \n",
+ " sgd = optimizers.SGD(lr=eta)\n",
+ " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
+ " \n",
+ " return model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
+ " \n",
+ "for i, eta in enumerate(eta_vals):\n",
+ " for j, lmbd in enumerate(lmbd_vals):\n",
+ " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n",
+ " eta=eta, lmbd=lmbd)\n",
+ " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
+ " scores = DNN.evaluate(X_test, Y_test)\n",
+ " \n",
+ " DNN_keras[i][j] = DNN\n",
+ " \n",
+ " print(\"Learning rate = \", eta)\n",
+ " print(\"Lambda = \", lmbd)\n",
+ " print(\"Test accuracy: %.3f\" % scores[1])\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# optional\n",
+ "# visual representation of grid search\n",
+ "# uses seaborn heatmap, could probably do this in matplotlib\n",
+ "import seaborn as sns\n",
+ "\n",
+ "sns.set()\n",
+ "\n",
+ "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
+ "\n",
+ "for i in range(len(eta_vals)):\n",
+ " for j in range(len(lmbd_vals)):\n",
+ " DNN = DNN_keras[i][j]\n",
+ "\n",
+ " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n",
+ " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n",
+ "\n",
+ " \n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Training Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()\n",
+ "\n",
+ "fig, ax = plt.subplots(figsize = (10, 10))\n",
+ "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
+ "ax.set_title(\"Test Accuracy\")\n",
+ "ax.set_ylabel(\"$\\eta$\")\n",
+ "ax.set_xlabel(\"$\\lambda$\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The Breast Cancer Data, now with Keras"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "import tensorflow as tf\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
+ "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
+ "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
+ "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
+ "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import seaborn as sns\n",
+ "from sklearn.model_selection import train_test_split as splitter\n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "import pickle\n",
+ "import os \n",
+ "\n",
+ "\n",
+ "\"\"\"Load breast cancer dataset\"\"\"\n",
+ "\n",
+ "np.random.seed(0) #create same seed for random number every time\n",
+ "\n",
+ "cancer=load_breast_cancer() #Download breast cancer dataset\n",
+ "\n",
+ "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n",
+ "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n",
+ "labels=cancer.feature_names[0:30]\n",
+ "\n",
+ "print('The content of the breast cancer dataset is:') #Print information about the datasets\n",
+ "print(labels)\n",
+ "print('-------------------------')\n",
+ "print(\"inputs = \" + str(inputs.shape))\n",
+ "print(\"outputs = \" + str(outputs.shape))\n",
+ "print(\"labels = \"+ str(labels.shape))\n",
+ "\n",
+ "x=inputs #Reassign the Feature and Label matrices to other variables\n",
+ "y=outputs\n",
+ "\n",
+ "#%% \n",
+ "\n",
+ "# Visualisation of dataset (for correlation analysis)\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean radius',fontweight='bold')\n",
+ "plt.ylabel('Mean perimeter',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean compactness',fontweight='bold')\n",
+ "plt.ylabel('Mean concavity',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean radius',fontweight='bold')\n",
+ "plt.ylabel('Mean texture',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean perimeter',fontweight='bold')\n",
+ "plt.ylabel('Mean compactness',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "# Generate training and testing datasets\n",
+ "\n",
+ "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n",
+ "#and add to input matrix\n",
+ "\n",
+ "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n",
+ "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n",
+ "X=np.hstack((temp1,temp2)) \n",
+ "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n",
+ "X=np.hstack((X,temp)) \n",
+ "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n",
+ "X=np.hstack((X,temp)) \n",
+ "\n",
+ "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n",
+ "\n",
+ "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n",
+ "y_test=to_categorical(y_test)\n",
+ "\n",
+ "del temp1,temp2,temp\n",
+ "\n",
+ "# %%\n",
+ "\n",
+ "# Define tunable parameters\"\n",
+ "\n",
+ "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n",
+ "lamda=0.01 #Define hyperparameter\n",
+ "n_layers=2 #Define number of hidden layers in the model\n",
+ "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n",
+ "epochs=100 #Number of reiterations over the input data\n",
+ "batch_size=100 #Number of samples per gradient update\n",
+ "\n",
+ "# %%\n",
+ "\n",
+ "\"\"\"Define function to return Deep Neural Network model\"\"\"\n",
+ "\n",
+ "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n",
+ " model=Sequential() \n",
+ " for i in range(n_layers): #Run loop to add hidden layers to the model\n",
+ " if (i==0): #First layer requires input dimensions\n",
+ " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n",
+ " else: #Subsequent layers are capable of automatic shape inferencing\n",
+ " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n",
+ " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n",
+ " sgd=optimizers.SGD(lr=eta)\n",
+ " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n",
+ " return model\n",
+ "\n",
+ " \n",
+ "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n",
+ "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n",
+ "\n",
+ "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n",
+ " for j in range(len(eta)): #accuracy scores \n",
+ " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n",
+ " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n",
+ " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n",
+ " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n",
+ " \n",
+ "\n",
+ "def plot_data(x,y,data,title=None):\n",
+ "\n",
+ " # plot results\n",
+ " fontsize=16\n",
+ "\n",
+ "\n",
+ " fig = plt.figure()\n",
+ " ax = fig.add_subplot(111)\n",
+ " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n",
+ " \n",
+ " cbar=fig.colorbar(cax)\n",
+ " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n",
+ " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n",
+ " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n",
+ "\n",
+ " # put text on matrix elements\n",
+ " for i, x_val in enumerate(np.arange(len(x))):\n",
+ " for j, y_val in enumerate(np.arange(len(y))):\n",
+ " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n",
+ " ax.text(x_val, y_val, c, va='center', ha='center')\n",
+ "\n",
+ " # convert axis vaues to to string labels\n",
+ " x=[str(i) for i in x]\n",
+ " y=[str(i) for i in y]\n",
+ "\n",
+ "\n",
+ " ax.set_xticklabels(['']+x)\n",
+ " ax.set_yticklabels(['']+y)\n",
+ "\n",
+ " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n",
+ " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n",
+ " if title is not None:\n",
+ " ax.set_title(title)\n",
+ "\n",
+ " plt.tight_layout()\n",
+ "\n",
+ " plt.show()\n",
+ " \n",
+ "plot_data(eta,n_neuron,Train_accuracy, 'training')\n",
+ "plot_data(eta,n_neuron,Test_accuracy, 'testing')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Fine-tuning neural network hyperparameters\n",
+ "\n",
+ "The flexibility of neural networks is also one of their main\n",
+ "drawbacks: there are many hyperparameters to tweak. Not only can you\n",
+ "use any imaginable network topology (how neurons/nodes are interconnected),\n",
+ "but even in a simple FFNN you can change the number of layers, the\n",
+ "number of neurons per layer, the type of activation function to use in\n",
+ "each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you\n",
+ "know what combination of hyperparameters is the best for your task?\n",
+ "\n",
+ "* You can use grid search with cross-validation to find the right hyperparameters.\n",
+ "\n",
+ "However,since there are many hyperparameters to tune, and since\n",
+ "training a neural network on a large dataset takes a lot of time, you\n",
+ "will only be able to explore a tiny part of the hyperparameter space.\n",
+ "\n",
+ "\n",
+ "* You can use randomized search.\n",
+ "\n",
+ "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly. \n",
+ "\n",
+ "For many problems you can start with just one or two hidden layers and it will work just fine.\n",
+ "For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a\n",
+ "few hundred neurons.\n",
+ "You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of\n",
+ "neurons, in roughly the same amount of training time. \n",
+ "\n",
+ "For more complex problems, you can gradually\n",
+ "ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such\n",
+ "as large image classification or speech recognition, typically require networks with dozens of layers\n",
+ "and they need a huge amount\n",
+ "of training data. However, you will rarely have to train such networks from scratch: it is much more\n",
+ "common to reuse parts of a pretrained state-of-the-art network that performs a similar task.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Which activation function should I use?\n",
+ "\n",
+ "The Back propagation algorithm we derived above works by going from\n",
+ "the output layer to the input layer, propagating the error gradient on\n",
+ "the way. Once the algorithm has computed the gradient of the cost\n",
+ "function with regards to each parameter in the network, it uses these\n",
+ "gradients to update each parameter with a Gradient Descent (GD) step.\n",
+ "\n",
+ "\n",
+ "Unfortunately for us, the gradients often get smaller and smaller as the\n",
+ "algorithm progresses down to the first hidden layers. As a result, the\n",
+ "GD update leaves the lower layer connection weights\n",
+ "virtually unchanged, and training never converges to a good\n",
+ "solution. This is known in the literature as \n",
+ "**the vanishing gradients problem**. \n",
+ "\n",
+ "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n",
+ "bigger. The result is that many of the layers get large updates of the \n",
+ "weights the\n",
+ "algorithm diverges. This is the **exploding gradients problem**, which is\n",
+ "mostly encountered in recurrent neural networks. More generally, deep\n",
+ "neural networks suffer from unstable gradients, different layers may\n",
+ "learn at widely different speeds\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Although this unfortunate behavior has been empirically observed for\n",
+ "quite a while (it was one of the reasons why deep neural networks were\n",
+ "mostly abandoned for a long time), it is only around 2010 that\n",
+ "significant progress was made in understanding it.\n",
+ "\n",
+ "A paper titled [Understanding the Difficulty of Training Deep\n",
+ "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n",
+ "the problems with the popular logistic\n",
+ "sigmoid activation function and the weight initialization technique\n",
+ "that was most popular at the time, namely random initialization using\n",
+ "a normal distribution with a mean of 0 and a standard deviation of\n",
+ "1. \n",
+ "\n",
+ "They showed that with this activation function and this\n",
+ "initialization scheme, the variance of the outputs of each layer is\n",
+ "much greater than the variance of its inputs. Going forward in the\n",
+ "network, the variance keeps increasing after each layer until the\n",
+ "activation function saturates at the top layers. This is actually made\n",
+ "worse by the fact that the logistic function has a mean of 0.5, not 0\n",
+ "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n",
+ "better than the logistic function in deep networks).\n",
+ "\n",
+ "\n",
+ "\n",
+ "Looking at the logistic activation function, when inputs become large\n",
+ "(negative or positive), the function saturates at 0 or 1, with a\n",
+ "derivative extremely close to 0. Thus when backpropagation kicks in,\n",
+ "it has virtually no gradient to propagate back through the network,\n",
+ "and what little gradient exists keeps getting diluted as\n",
+ "backpropagation progresses down through the top layers, so there is\n",
+ "really nothing left for the lower layers.\n",
+ "\n",
+ "In their paper, Glorot and Bengio propose a way to significantly\n",
+ "alleviate this problem. We need the signal to flow properly in both\n",
+ "directions: in the forward direction when making predictions, and in\n",
+ "the reverse direction when backpropagating gradients. We don’t want\n",
+ "the signal to die out, nor do we want it to explode and saturate. For\n",
+ "the signal to flow properly, the authors argue that we need the\n",
+ "variance of the outputs of each layer to be equal to the variance of\n",
+ "its inputs, and we also need the gradients to have equal variance\n",
+ "before and after flowing through a layer in the reverse direction.\n",
+ "\n",
+ "\n",
+ "\n",
+ "One of the insights in the 2010 paper by Glorot and Bengio was that\n",
+ "the vanishing/exploding gradients problems were in part due to a poor\n",
+ "choice of activation function. Until then most people had assumed that\n",
+ "if Nature had chosen to use roughly sigmoid activation functions in\n",
+ "biological neurons, they must be an excellent choice. But it turns out\n",
+ "that other activation functions behave much better in deep neural\n",
+ "networks, in particular the ReLU activation function, mostly because\n",
+ "it does not saturate for positive values (and also because it is quite\n",
+ "fast to compute).\n",
+ "\n",
+ "\n",
+ "## The RELU function family\n",
+ "\n",
+ "The ReLU activation function suffers from a problem known as the dying\n",
+ "ReLUs: during training, some neurons effectively die, meaning they\n",
+ "stop outputting anything other than 0.\n",
+ "\n",
+ "In some cases, you may find that half of your network’s neurons are\n",
+ "dead, especially if you used a large learning rate. During training,\n",
+ "if a neuron’s weights get updated such that the weighted sum of the\n",
+ "neuron’s inputs is negative, it will start outputting 0. When this\n",
+ "happen, the neuron is unlikely to come back to life since the gradient\n",
+ "of the ReLU function is 0 when its input is negative.\n",
+ "\n",
+ "To solve this problem, nowadays practitioners use a variant of the ReLU\n",
+ "function, such as the leaky ReLU discussed above or the so-called\n",
+ "exponential linear unit (ELU) function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In general it seems that the ELU activation function is better than\n",
+ "the leaky ReLU function (and its variants), which is better than\n",
+ "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n",
+ "than the logistic function. \n",
+ "\n",
+ "If runtime\n",
+ "performance is an issue, then you may opt for the leaky ReLU function over the \n",
+ "ELU function If you don’t\n",
+ "want to tweak yet another hyperparameter, you may just use the default\n",
+ "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n",
+ "spare time and computing power, you can use cross-validation or\n",
+ "bootstrap to evaluate other activation functions.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).\n",
+ "\n",
+ "It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.\n",
+ "\n",
+ "**For the output layer:**\n",
+ "\n",
+ "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n",
+ "\n",
+ "* For regression tasks, you can simply use no activation function at all.\n",
+ "\n",
+ "## Batch Normalization\n",
+ "\n",
+ "Batch Normalization\n",
+ "aims to address the vanishing/exploding gradients problems, and more generally the problem that the\n",
+ "distribution of each layer’s inputs changes during training, as the parameters of the previous layers change.\n",
+ "\n",
+ "The technique consists of adding an operation in the model just before the activation function of each\n",
+ "layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new\n",
+ "parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model\n",
+ "learn the optimal scale and mean of the inputs for each layer.\n",
+ "In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and\n",
+ "standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current\n",
+ "mini-batch, from this the name batch normalization.\n",
+ "\n",
+ "## Dropout\n",
+ "\n",
+ "It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but\n",
+ "excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be\n",
+ "entirely ignored during this training step, but it may be active during the next step.\n",
+ "\n",
+ "The\n",
+ "hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.\n",
+ " It is viewed as one of the most popular regularization techniques.\n",
+ "\n",
+ "## Gradient Clipping\n",
+ "\n",
+ "A popular technique to lessen the exploding gradients problem is to simply clip the gradients during\n",
+ "backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural\n",
+ "networks).\n",
+ "\n",
+ "This technique is called Gradient Clipping.\n",
+ "\n",
+ "In general however, Batch\n",
+ "Normalization is preferred.\n",
+ "\n",
+ "\n",
+ "## A top-down perspective on Neural networks\n",
+ "\n",
+ "\n",
+ "The first thing we would like to do is divide the data into two or three\n",
+ "parts. A training set, a validation or dev (development) set, and a\n",
+ "test set. The test set is the data on which we want to make\n",
+ "predictions. The dev set is a subset of the training data we use to\n",
+ "check how well we are doing out-of-sample, after training the model on\n",
+ "the training dataset. We use the validation error as a proxy for the\n",
+ "test error in order to make tweaks to our model. It is crucial that we\n",
+ "do not use any of the test data to train the algorithm. This is a\n",
+ "cardinal sin in ML. Then:\n",
+ "\n",
+ "\n",
+ "* Estimate optimal error rate\n",
+ "\n",
+ "* Minimize underfitting (bias) on training data set.\n",
+ "\n",
+ "* Make sure you are not overfitting.\n",
+ "\n",
+ "If the validation and test sets are drawn from the same distributions,\n",
+ "then a good performance on the validation set should lead to similarly\n",
+ "good performance on the test set. \n",
+ "\n",
+ "However, sometimes\n",
+ "the training data and test data differ in subtle ways because, for\n",
+ "example, they are collected using slightly different methods, or\n",
+ "because it is cheaper to collect data in one way versus another. In\n",
+ "this case, there can be a mismatch between the training and test\n",
+ "data. This can lead to the neural network overfitting these small\n",
+ "differences between the test and training sets, and a poor performance\n",
+ "on the test set despite having a good performance on the validation\n",
+ "set. To rectify this, Andrew Ng suggests making two validation or dev\n",
+ "sets, one constructed from the training data and one constructed from\n",
+ "the test data. The difference between the performance of the algorithm\n",
+ "on these two validation sets quantifies the train-test mismatch. This\n",
+ "can serve as another important diagnostic when using DNNs for\n",
+ "supervised learning.\n",
+ "\n",
+ "\n",
+ "## Limitations of supervised learning with deep networks\n",
+ "\n",
+ "Like all statistical methods, supervised learning using neural\n",
+ "networks has important limitations. This is especially important when\n",
+ "one seeks to apply these methods, especially to physics problems. Like\n",
+ "all tools, DNNs are not a universal solution. Often, the same or\n",
+ "better performance on a task can be achieved by using a few\n",
+ "hand-engineered features (or even a collection of random\n",
+ "features). \n",
+ "\n",
+ "Here we list some of the important limitations of supervised neural network based models. \n",
+ "\n",
+ "\n",
+ "\n",
+ "* **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).\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "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."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter11.ipynb b/doc/LectureNotes/_build/html/_sources/chapter11.ipynb
new file mode 100644
index 000000000..c03e4a368
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter11.ipynb
@@ -0,0 +1,3023 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Solving Differential Equations with Deep Learning\n",
+ "\n",
+ "The Universal Approximation Theorem states that a neural network can\n",
+ "approximate any function at a single hidden layer along with one input\n",
+ "and output layer to any given precision. \n",
+ "\n",
+ "\n",
+ "An ordinary differential equation (ODE) is an equation involving functions having one variable.\n",
+ "\n",
+ "In general, an ordinary differential equation looks like"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "
\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{ode} \\tag{1}\n",
+ "f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right) = 0\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n",
+ "\n",
+ "The $f\\left(x, g(x), g'(x), g''(x), \\, \\dots \\, , g^{(n)}(x)\\right)$ is just a way to write that there is an expression involving $x$ and $g(x), \\ g'(x), \\ g''(x), \\, \\dots \\, , \\text{ and } g^{(n)}(x)$ on the left side of the equality sign in ([1](#ode)).\n",
+ "The highest order of derivative, that is the value of $n$, determines to the order of the equation.\n",
+ "The equation is referred to as a $n$-th order ODE.\n",
+ "Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n",
+ "for the solution to be unique.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let the trial solution $g_t(x)$ be"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\tg_t(x) = h_1(x) + h_2(x,N(x,P))\n",
+ "\\label{_auto1} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set\n",
+ "of conditions, $N(x,P)$ a neural network with weights and biases\n",
+ "described by $P$ and $h_2(x, N(x,P))$ some expression involving the\n",
+ "neural network. The role of the function $h_2(x, N(x,P))$, is to\n",
+ "ensure that the output from $N(x,P)$ is zero when $g_t(x)$ is\n",
+ "evaluated at the values of $x$ where the given conditions must be\n",
+ "satisfied. The function $h_1(x)$ should alone make $g_t(x)$ satisfy\n",
+ "the conditions.\n",
+ "\n",
+ "But what about the network $N(x,P)$?\n",
+ "\n",
+ "\n",
+ "As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the minimization to be defined, we need to have a cost function at hand to minimize.\n",
+ "\n",
+ "It is given that $f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)$ should be equal to zero in ([1](#ode)).\n",
+ "We can choose to consider the mean squared error as the cost function for an input $x$.\n",
+ "Since we are looking at one input, the cost function is just $f$ squared.\n",
+ "The cost function $c\\left(x, P \\right)$ can therefore be expressed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C\\left(x, P\\right) = \\big(f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)\\big)^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If $N$ inputs are given as a vector $\\boldsymbol{x}$ with elements $x_i$ for $i = 1,\\dots,N$,\n",
+ "the cost function becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{cost} \\tag{3}\n",
+ "\tC\\left(\\boldsymbol{x}, P\\right) = \\frac{1}{N} \\sum_{i=1}^N \\big(f\\left(x_i, \\, g(x_i), \\, g'(x_i), \\, g''(x_i), \\, \\dots \\, , \\, g^{(n)}(x_i)\\right)\\big)^2\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The neural net should then find the parameters $P$ that minimizes the cost function in\n",
+ "([3](#cost)) for a set of $N$ training samples $x_i$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "To perform the minimization using gradient descent, the gradient of $C\\left(\\boldsymbol{x}, P\\right)$ is needed.\n",
+ "It might happen so that finding an analytical expression of the gradient of $C(\\boldsymbol{x}, P)$ from ([3](#cost)) gets too messy, depending on which cost function one desires to use.\n",
+ "\n",
+ "Luckily, there exists libraries that makes the job for us through automatic differentiation.\n",
+ "Automatic differentiation is a method of finding the derivatives numerically with very high precision.\n",
+ "\n",
+ "\n",
+ "### Example: Exponential decay\n",
+ "\n",
+ "An exponential decay of a quantity $g(x)$ is described by the equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{solve_expdec} \\tag{4}\n",
+ " g'(x) = -\\gamma g(x)\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $g(0) = g_0$ for some chosen initial value $g_0$.\n",
+ "\n",
+ "The analytical solution of ([4](#solve_expdec)) is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " g(x) = g_0 \\exp\\left(-\\gamma x\\right)\n",
+ "\\label{_auto2} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of ([4](#solve_expdec)).\n",
+ "\n",
+ "\n",
+ "\n",
+ "The program will use a neural network to solve"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{solveode} \\tag{6}\n",
+ "g'(x) = -\\gamma g(x)\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $g(0) = g_0$ with $\\gamma$ and $g_0$ being some chosen values.\n",
+ "\n",
+ "In this example, $\\gamma = 2$ and $g_0 = 10$.\n",
+ "\n",
+ "\n",
+ "To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $h_1(x)$ ensuring that $g_t(x)$ satisfies some conditions and $h_2(x,N(x, P))$ an expression involving $x$ and the output from the neural network $N(x,P)$ with $P $ being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In this network, there are no weights and bias at the input layer, so $P = \\{ P_{\\text{hidden}}, P_{\\text{output}} \\}$.\n",
+ "If there are $N_{\\text{hidden} }$ neurons in the hidden layer, then $P_{\\text{hidden}}$ is a $N_{\\text{hidden} } \\times (1 + N_{\\text{input}})$ matrix, given that there are $N_{\\text{input}}$ neurons in the input layer.\n",
+ "\n",
+ "The first column in $P_{\\text{hidden} }$ represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.\n",
+ "If there are $N_{\\text{output} }$ neurons in the output layer, then $P_{\\text{output}} $ is a $N_{\\text{output} } \\times (1 + N_{\\text{hidden} })$ matrix.\n",
+ "\n",
+ "Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.\n",
+ "\n",
+ "It is given that $g(0) = g_0$. The trial solution must fulfill this condition to be a proper solution of ([6](#solveode)). A possible way to ensure that $g_t(0, P) = g_0$, is to let $F(N(x,P)) = x \\cdot N(x,P)$ and $A(x) = g_0$. This gives the following trial solution:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{trial} \\tag{7}\n",
+ "g_t(x, P) = g_0 + x \\cdot N(x, P)\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Reformulating the problem\n",
+ "\n",
+ "We wish that our neural network manages to minimize a given cost function.\n",
+ "\n",
+ "A reformulation of out equation, ([6](#solveode)), must therefore be done,\n",
+ "such that it describes the problem a neural network can solve for.\n",
+ "\n",
+ "The neural network must find the set of weights and biases $P$ such that the trial solution in ([7](#trial)) satisfies ([6](#solveode)).\n",
+ "\n",
+ "The trial solution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "g_t(x, P) = g_0 + x \\cdot N(x, P)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{nnmin} \\tag{8}\n",
+ "g_t'(x, P) = - \\gamma g_t(x, P)\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is fulfilled as *best as possible*.\n",
+ "\n",
+ "\n",
+ "The left hand side and right hand side of ([8](#nnmin)) must be computed separately, and then the neural network must choose weights and biases, contained in $P$, such that the sides are equal as best as possible.\n",
+ "This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.\n",
+ "In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to $P$ of the neural network.\n",
+ "\n",
+ "This gives the following cost function our neural network must solve for:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "(the notation $\\min_{P}\\{ f(x, P) \\}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$)\n",
+ "\n",
+ "or, in terms of weights and biases for the hidden and output layer in our network:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }}\\Big\\{ \\big(g_t'(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) - ( -\\gamma g_t(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) \\big)^2 \\Big\\}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for an input value $x$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If the neural network evaluates $g_t(x, P)$ at more values for $x$, say $N$ values $x_i$ for $i = 1, \\dots, N$, then the *total* error to minimize becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{min} \\tag{9}\n",
+ "\\min_{P}\\Big\\{\\frac{1}{N} \\sum_{i=1}^N \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2 \\Big\\}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Letting $\\boldsymbol{x}$ be a vector with elements $x_i$ and $C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2$ denote the cost function, the minimization problem that our network must solve, becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\min_{P} C(\\boldsymbol{x}, P)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n",
+ "\n",
+ "$$\n",
+ "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n",
+ "$$\n",
+ "\n",
+ "\n",
+ "For simplicity, it is assumed that the input is an array $\\boldsymbol{x} = (x_1, \\dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills ([9](#min)).\n",
+ "\n",
+ "First, the neural network must feed forward the inputs.\n",
+ "This means that $\\boldsymbol{x}s$ must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.\n",
+ "The input layer will consist of $N_{\\text{input} }$ neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be $N_{\\text{hidden} }$.\n",
+ "\n",
+ "\n",
+ "For the $i$-th in the hidden layer with weight $w_i^{\\text{hidden} }$ and bias $b_i^{\\text{hidden} }$, the weighting from the $j$-th neuron at the input layer is:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "z_{i,j}^{\\text{hidden}} &= b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_j \\\\\n",
+ "&=\n",
+ "\\begin{pmatrix}\n",
+ "b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n",
+ "\\end{pmatrix}\n",
+ "\\begin{pmatrix}\n",
+ "1 \\\\\n",
+ "x_j\n",
+ "\\end{pmatrix}\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "\\boldsymbol{z}_{i}^{\\text{hidden}} &= \\Big( b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_1 , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_2, \\ \\dots \\, , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_N\\Big) \\\\\n",
+ "&=\n",
+ "\\begin{pmatrix}\n",
+ " b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n",
+ "\\end{pmatrix}\n",
+ "\\begin{pmatrix}\n",
+ "1 & 1 & \\dots & 1 \\\\\n",
+ "x_1 & x_2 & \\dots & x_N\n",
+ "\\end{pmatrix} \\\\\n",
+ "&= \\boldsymbol{p}_{i, \\text{hidden}}^T X\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The vector $\\boldsymbol{p}_{i, \\text{hidden}}^T$ constitutes each row in $P_{\\text{hidden} }$, which contains the weights for the neural network to minimize according to ([9](#min)).\n",
+ "\n",
+ "After having found $\\boldsymbol{z}_{i}^{\\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\\boldsymbol{z})$.\n",
+ "\n",
+ "In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is possible to use other activations functions for the hidden layer also.\n",
+ "\n",
+ "The output $\\boldsymbol{x}_i^{\\text{hidden}}$ from each $i$-th hidden neuron is:\n",
+ "\n",
+ "$$\n",
+ "\\boldsymbol{x}_i^{\\text{hidden} } = f\\big( \\boldsymbol{z}_{i}^{\\text{hidden}} \\big)\n",
+ "$$\n",
+ "\n",
+ "The outputs $\\boldsymbol{x}_i^{\\text{hidden} } $ are then sent to the output layer.\n",
+ "\n",
+ "The output layer consists of one neuron in this case, and combines the\n",
+ "output from each of the neurons in the hidden layers. The output layer\n",
+ "combines the results from the hidden layer using some weights $w_i^{\\text{output}}$\n",
+ "and biases $b_i^{\\text{output}}$. In this case,\n",
+ "it is assumes that the number of neurons in the output layer is one.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The procedure of weighting the output neuron $j$ in the hidden layer to the $i$-th neuron in the output layer is similar as for the hidden layer described previously."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "z_{1,j}^{\\text{output}} & =\n",
+ "\\begin{pmatrix}\n",
+ "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n",
+ "\\end{pmatrix}\n",
+ "\\begin{pmatrix}\n",
+ "1 \\\\\n",
+ "\\boldsymbol{x}_j^{\\text{hidden}}\n",
+ "\\end{pmatrix}\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Expressing $z_{1,j}^{\\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{z}_{1}^{\\text{output}} =\n",
+ "\\begin{pmatrix}\n",
+ "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n",
+ "\\end{pmatrix}\n",
+ "\\begin{pmatrix}\n",
+ "1 & 1 & \\dots & 1 \\\\\n",
+ "\\boldsymbol{x}_1^{\\text{hidden}} & \\boldsymbol{x}_2^{\\text{hidden}} & \\dots & \\boldsymbol{x}_N^{\\text{hidden}}\n",
+ "\\end{pmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\\boldsymbol{z}_{1}^{\\text{output}}$ the neural network has finished its feed forward step, and $\\boldsymbol{z}_{1}^{\\text{output}}$ is the final output of the network.\n",
+ "\n",
+ "\n",
+ "The next step is to decide how the parameters should be changed such that they minimize the cost function.\n",
+ "\n",
+ "The chosen cost function for this problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In order to minimize the cost function, an optimization method must be chosen.\n",
+ "\n",
+ "Here, gradient descent with a constant step size has been chosen.\n",
+ "\n",
+ "### Gradient descent\n",
+ "\n",
+ "The idea of the gradient descent algorithm is to update parameters in\n",
+ "a direction where the cost function decreases goes to a minimum.\n",
+ "\n",
+ "In general, the update of some parameters $\\boldsymbol{\\omega}$ given a cost\n",
+ "function defined by some weights $\\boldsymbol{\\omega}$, $C(\\boldsymbol{x},\n",
+ "\\boldsymbol{\\omega})$, goes as follows:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for a number of iterations or until $ \\big|\\big| \\boldsymbol{\\omega}_{\\text{new} } - \\boldsymbol{\\omega} \\big|\\big|$ becomes smaller than some given tolerance.\n",
+ "\n",
+ "The value of $\\lambda$ decides how large steps the algorithm must take\n",
+ "in the direction of $ \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})$.\n",
+ "The notation $\\nabla_{\\boldsymbol{\\omega}}$ express the gradient with respect\n",
+ "to the elements in $\\boldsymbol{\\omega}$.\n",
+ "\n",
+ "In our case, we have to minimize the cost function $C(\\boldsymbol{x}, P)$ with\n",
+ "respect to the two sets of weights and biases, that is for the hidden\n",
+ "layer $P_{\\text{hidden} }$ and for the output layer $P_{\\text{output}\n",
+ "}$ .\n",
+ "\n",
+ "This means that $P_{\\text{hidden} }$ and $P_{\\text{output} }$ is updated by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "P_{\\text{hidden},\\text{new}} &= P_{\\text{hidden}} - \\lambda \\nabla_{P_{\\text{hidden}}} C(\\boldsymbol{x}, P) \\\\\n",
+ "P_{\\text{output},\\text{new}} &= P_{\\text{output}} - \\lambda \\nabla_{P_{\\text{output}}} C(\\boldsymbol{x}, P)\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### The code for solving the ODE"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import autograd.numpy as np\n",
+ "from autograd import grad, elementwise_grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import pyplot as plt\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "# Assuming one input, hidden, and output layer\n",
+ "def neural_network(params, x):\n",
+ "\n",
+ " # Find the weights (including and biases) for the hidden and output layer.\n",
+ " # Assume that params is a list of parameters for each layer.\n",
+ " # The biases are the first element for each array in params,\n",
+ " # and the weights are the remaning elements in each array in params.\n",
+ "\n",
+ " w_hidden = params[0]\n",
+ " w_output = params[1]\n",
+ "\n",
+ " # Assumes input x being an one-dimensional array\n",
+ " num_values = np.size(x)\n",
+ " x = x.reshape(-1, num_values)\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ "\n",
+ " ## Hidden layer:\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_input)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Include bias:\n",
+ " x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_hidden)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output\n",
+ "\n",
+ "# The trial solution using the deep neural network:\n",
+ "def g_trial(x,params, g0 = 10):\n",
+ " return g0 + x*neural_network(params,x)\n",
+ "\n",
+ "# The right side of the ODE:\n",
+ "def g(x, g_trial, gamma = 2):\n",
+ " return -gamma*g_trial\n",
+ "\n",
+ "# The cost function:\n",
+ "def cost_function(P, x):\n",
+ "\n",
+ " # Evaluate the trial function with the current parameters P\n",
+ " g_t = g_trial(x,P)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the neural network\n",
+ " d_net_out = elementwise_grad(neural_network,1)(P,x)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the trial function\n",
+ " d_g_t = elementwise_grad(g_trial,0)(x,P)\n",
+ "\n",
+ " # The right side of the ODE\n",
+ " func = g(x, g_t)\n",
+ "\n",
+ " err_sqr = (d_g_t - func)**2\n",
+ " cost_sum = np.sum(err_sqr)\n",
+ "\n",
+ " return cost_sum / np.size(err_sqr)\n",
+ "\n",
+ "# Solve the exponential decay ODE using neural network with one input, hidden, and output layer\n",
+ "def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb):\n",
+ " ## Set up initial weights and biases\n",
+ "\n",
+ " # For the hidden layer\n",
+ " p0 = npr.randn(num_neurons_hidden, 2 )\n",
+ "\n",
+ " # For the output layer\n",
+ " p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included\n",
+ "\n",
+ " P = [p0, p1]\n",
+ "\n",
+ " print('Initial cost: %g'%cost_function(P, x))\n",
+ "\n",
+ " ## Start finding the optimal weights using gradient descent\n",
+ "\n",
+ " # Find the Python function that represents the gradient of the cost function\n",
+ " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
+ " cost_function_grad = grad(cost_function,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " # Evaluate the gradient at the current weights and biases in P.\n",
+ " # The cost_grad consist now of two arrays;\n",
+ " # one for the gradient w.r.t P_hidden and\n",
+ " # one for the gradient w.r.t P_output\n",
+ " cost_grad = cost_function_grad(P, x)\n",
+ "\n",
+ " P[0] = P[0] - lmb * cost_grad[0]\n",
+ " P[1] = P[1] - lmb * cost_grad[1]\n",
+ "\n",
+ " print('Final cost: %g'%cost_function(P, x))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "def g_analytic(x, gamma = 2, g0 = 10):\n",
+ " return g0*np.exp(-gamma*x)\n",
+ "\n",
+ "# Solve the given problem\n",
+ "if __name__ == '__main__':\n",
+ " # Set seed such that the weight are initialized\n",
+ " # with same weights and biases for every run.\n",
+ " npr.seed(15)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " N = 10\n",
+ " x = np.linspace(0, 1, N)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = 10\n",
+ " num_iter = 10000\n",
+ " lmb = 0.001\n",
+ "\n",
+ " # Use the network\n",
+ " P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " # Print the deviation from the trial solution and true solution\n",
+ " res = g_trial(x,P)\n",
+ " res_analytical = g_analytic(x)\n",
+ "\n",
+ " print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical)))\n",
+ "\n",
+ " # Plot the results\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(x, res_analytical)\n",
+ " plt.plot(x, res[0,:])\n",
+ " plt.legend(['analytical','nn'])\n",
+ " plt.xlabel('x')\n",
+ " plt.ylabel('g(x)')\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The network with one input layer, specified number of hidden layers, and one output layer\n",
+ "\n",
+ "It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.\n",
+ "\n",
+ "The number of neurons within each hidden layer are given as a list of integers in the program below."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad, elementwise_grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import pyplot as plt\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "# The neural network with one input layer and one output layer,\n",
+ "# but with number of hidden layers specified by the user.\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # N_hidden is the number of hidden layers\n",
+ "\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consists of\n",
+ " # parameters to all the hidden\n",
+ " # layers AND the output layer.\n",
+ "\n",
+ " # Assumes input x being an one-dimensional array\n",
+ " num_values = np.size(x)\n",
+ " x = x.reshape(-1, num_values)\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ "\n",
+ " # Due to multiple hidden layers, define a variable referencing to the\n",
+ " # output of the previous layer:\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output\n",
+ "\n",
+ "# The trial solution using the deep neural network:\n",
+ "def g_trial_deep(x,params, g0 = 10):\n",
+ " return g0 + x*deep_neural_network(params, x)\n",
+ "\n",
+ "# The right side of the ODE:\n",
+ "def g(x, g_trial, gamma = 2):\n",
+ " return -gamma*g_trial\n",
+ "\n",
+ "# The same cost function as before, but calls deep_neural_network instead.\n",
+ "def cost_function_deep(P, x):\n",
+ "\n",
+ " # Evaluate the trial function with the current parameters P\n",
+ " g_t = g_trial_deep(x,P)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the neural network\n",
+ " d_net_out = elementwise_grad(deep_neural_network,1)(P,x)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the trial function\n",
+ " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n",
+ "\n",
+ " # The right side of the ODE\n",
+ " func = g(x, g_t)\n",
+ "\n",
+ " err_sqr = (d_g_t - func)**2\n",
+ " cost_sum = np.sum(err_sqr)\n",
+ "\n",
+ " return cost_sum / np.size(err_sqr)\n",
+ "\n",
+ "# Solve the exponential decay ODE using neural network with one input and one output layer,\n",
+ "# but with specified number of hidden layers from the user.\n",
+ "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
+ " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
+ "\n",
+ " # The number of elements in the list num_hidden_neurons thus represents\n",
+ " # the number of hidden layers.\n",
+ "\n",
+ " # Find the number of hidden layers:\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weights and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 )\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " ## Start finding the optimal weights using gradient descent\n",
+ "\n",
+ " # Find the Python function that represents the gradient of the cost function\n",
+ " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
+ " cost_function_deep_grad = grad(cost_function_deep,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " # Evaluate the gradient at the current weights and biases in P.\n",
+ " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
+ " # in the hidden layers and output layers evaluated at x.\n",
+ " cost_deep_grad = cost_function_deep_grad(P, x)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_deep_grad[l]\n",
+ "\n",
+ " print('Final cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "def g_analytic(x, gamma = 2, g0 = 10):\n",
+ " return g0*np.exp(-gamma*x)\n",
+ "\n",
+ "# Solve the given problem\n",
+ "if __name__ == '__main__':\n",
+ " npr.seed(15)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " N = 10\n",
+ " x = np.linspace(0, 1, N)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = np.array([10,10])\n",
+ " num_iter = 10000\n",
+ " lmb = 0.001\n",
+ "\n",
+ " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " res = g_trial_deep(x,P)\n",
+ " res_analytical = g_analytic(x)\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(x, res_analytical)\n",
+ " plt.plot(x, res[0,:])\n",
+ " plt.legend(['analytical','dnn'])\n",
+ " plt.ylabel('g(x)')\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Example: Population growth\n",
+ "\n",
+ "A logistic model of population growth assumes that a population converges toward an equilibrium.\n",
+ "The population growth can be modeled by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{log} \\tag{10}\n",
+ "\tg'(t) = \\alpha g(t)(A - g(t))\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $g(t)$ is the population density at time $t$, $\\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment.\n",
+ "Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant.\n",
+ "\n",
+ "In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability\n",
+ "and high execution time (this might be more apparent in the examples solving PDEs),\n",
+ "using a library like TensorFlow is recommended.\n",
+ "Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n",
+ "The population follows the model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{solveode_population} \\tag{11}\n",
+ "g'(t) = \\alpha g(t)(A - g(t))\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $g(0) = g_0$.\n",
+ "\n",
+ "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$.\n",
+ "\n",
+ "\n",
+ "We will get a slightly different trial solution, as the boundary conditions are different\n",
+ "compared to the case for exponential decay.\n",
+ "\n",
+ "A possible trial solution satisfying the condition $g(0) = g_0$ could be\n",
+ "\n",
+ "$$\n",
+ "h_1(t) = g_0 + t \\cdot N(t,P)\n",
+ "$$\n",
+ "\n",
+ "with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$.\n",
+ "\n",
+ "The analytical solution is\n",
+ "\n",
+ "$$\n",
+ "g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n",
+ "$$\n",
+ "\n",
+ "\n",
+ "\n",
+ "The network will be the similar as for the exponential decay example, but with some small modifications for our problem."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad, elementwise_grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import pyplot as plt\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "# Function to get the parameters.\n",
+ "# Done such that one can easily change the paramaters after one's liking.\n",
+ "def get_parameters():\n",
+ " alpha = 2\n",
+ " A = 1\n",
+ " g0 = 1.2\n",
+ " return alpha, A, g0\n",
+ "\n",
+ "def deep_neural_network(P, x):\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(P) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assumes input x being an one-dimensional array\n",
+ " num_values = np.size(x)\n",
+ " x = x.reshape(-1, num_values)\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ "\n",
+ " # Due to multiple hidden layers, define a variable referencing to the\n",
+ " # output of the previous layer:\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = P[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = P[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output\n",
+ "\n",
+ "\n",
+ "def cost_function_deep(P, x):\n",
+ "\n",
+ " # Evaluate the trial function with the current parameters P\n",
+ " g_t = g_trial_deep(x,P)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the trial function\n",
+ " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n",
+ "\n",
+ " # The right side of the ODE\n",
+ " func = f(x, g_t)\n",
+ "\n",
+ " err_sqr = (d_g_t - func)**2\n",
+ " cost_sum = np.sum(err_sqr)\n",
+ "\n",
+ " return cost_sum / np.size(err_sqr)\n",
+ "\n",
+ "# The right side of the ODE:\n",
+ "def f(x, g_trial):\n",
+ " alpha,A, g0 = get_parameters()\n",
+ " return alpha*g_trial*(A - g_trial)\n",
+ "\n",
+ "# The trial solution using the deep neural network:\n",
+ "def g_trial_deep(x, params):\n",
+ " alpha,A, g0 = get_parameters()\n",
+ " return g0 + x*deep_neural_network(params,x)\n",
+ "\n",
+ "# The analytical solution:\n",
+ "def g_analytic(t):\n",
+ " alpha,A, g0 = get_parameters()\n",
+ " return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t))\n",
+ "\n",
+ "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
+ " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
+ "\n",
+ " # Find the number of hidden layers:\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weigths and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 )\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " ## Start finding the optimal weigths using gradient descent\n",
+ "\n",
+ " # Find the Python function that represents the gradient of the cost function\n",
+ " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
+ " cost_function_deep_grad = grad(cost_function_deep,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " # Evaluate the gradient at the current weights and biases in P.\n",
+ " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
+ " # in the hidden layers and output layers evaluated at x.\n",
+ " cost_deep_grad = cost_function_deep_grad(P, x)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_deep_grad[l]\n",
+ "\n",
+ " print('Final cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " npr.seed(4155)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nt = 10\n",
+ " T = 1\n",
+ " t = np.linspace(0,T, Nt)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = [100, 50, 25]\n",
+ " num_iter = 1000\n",
+ " lmb = 1e-3\n",
+ "\n",
+ " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " g_dnn_ag = g_trial_deep(t,P)\n",
+ " g_analytical = g_analytic(t)\n",
+ "\n",
+ " # Find the maximum absolute difference between the solutons:\n",
+ " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n",
+ " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(t, g_analytical)\n",
+ " plt.plot(t, g_dnn_ag[0,:])\n",
+ " plt.legend(['analytical','nn'])\n",
+ " plt.xlabel('t')\n",
+ " plt.ylabel('g(t)')\n",
+ "\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Using forward Euler to solve the ODE\n",
+ "\n",
+ "A straightforward way of solving an ODE numerically, is to use Euler's method.\n",
+ "\n",
+ "Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\\Delta x$ from $x$:\n",
+ "\n",
+ "$$\n",
+ "f(x + \\Delta x) \\approx f(x) + \\Delta x f'(x)\n",
+ "$$\n",
+ "\n",
+ "In our case, using Euler's method to approximate the value of $g$ at a step $\\Delta t$ from $t$ yields"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ " g(t + \\Delta t) &\\approx g(t) + \\Delta t g'(t) \\\\\n",
+ " &= g(t) + \\Delta t \\big(\\alpha g(t)(A - g(t))\\big)\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "along with the condition that $g(0) = g_0$.\n",
+ "\n",
+ "Let $t_i = i \\cdot \\Delta t$ where $\\Delta t = \\frac{T}{N_t-1}$ where $T$ is the final time our solver must solve for and $N_t$ the number of values for $t \\in [0, T]$ for $i = 0, \\dots, N_t-1$.\n",
+ "\n",
+ "For $i \\geq 1$, we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "t_i &= i\\Delta t \\\\\n",
+ "&= (i - 1)\\Delta t + \\Delta t \\\\\n",
+ "&= t_{i-1} + \\Delta t\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, if $g_i = g(t_i)$ then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\begin{aligned}\n",
+ " g_i &= g(t_i) \\\\\n",
+ " &= g(t_{i-1} + \\Delta t) \\\\\n",
+ " &\\approx g(t_{i-1}) + \\Delta t \\big(\\alpha g(t_{i-1})(A - g(t_{i-1}))\\big) \\\\\n",
+ " &= g_{i-1} + \\Delta t \\big(\\alpha g_{i-1}(A - g_{i-1})\\big)\n",
+ " \\end{aligned}\n",
+ "\\end{equation} \\label{odenum} \\tag{12}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n",
+ "\n",
+ "Equation ([12](#odenum)) could be implemented in the following way,\n",
+ "extending the program that uses the network using Autograd:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Assume that all function definitions from the example program using Autograd\n",
+ "# are located here.\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " npr.seed(4155)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nt = 10\n",
+ " T = 1\n",
+ " t = np.linspace(0,T, Nt)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = [100,50,25]\n",
+ " num_iter = 1000\n",
+ " lmb = 1e-3\n",
+ "\n",
+ " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " g_dnn_ag = g_trial_deep(t,P)\n",
+ " g_analytical = g_analytic(t)\n",
+ "\n",
+ " # Find the maximum absolute difference between the solutons:\n",
+ " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n",
+ " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(t, g_analytical)\n",
+ " plt.plot(t, g_dnn_ag[0,:])\n",
+ " plt.legend(['analytical','nn'])\n",
+ " plt.xlabel('t')\n",
+ " plt.ylabel('g(t)')\n",
+ "\n",
+ " ## Find an approximation to the funtion using forward Euler\n",
+ "\n",
+ " alpha, A, g0 = get_parameters()\n",
+ " dt = T/(Nt - 1)\n",
+ "\n",
+ " # Perform forward Euler to solve the ODE\n",
+ " g_euler = np.zeros(Nt)\n",
+ " g_euler[0] = g0\n",
+ "\n",
+ " for i in range(1,Nt):\n",
+ " g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1]))\n",
+ "\n",
+ " # Print the errors done by each method\n",
+ " diff1 = np.max(np.abs(g_euler - g_analytical))\n",
+ " diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical))\n",
+ "\n",
+ " print('Max absolute difference between Euler method and analytical: %g'%diff1)\n",
+ " print('Max absolute difference between deep neural network and analytical: %g'%diff2)\n",
+ "\n",
+ " # Plot results\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.plot(t,g_euler)\n",
+ " plt.plot(t,g_analytical)\n",
+ " plt.plot(t,g_dnn_ag[0,:])\n",
+ "\n",
+ " plt.legend(['euler','analytical','dnn'])\n",
+ " plt.xlabel('Time t')\n",
+ " plt.ylabel('g(t)')\n",
+ "\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Solving the one dimensional Poisson equation\n",
+ "\n",
+ "The Poisson equation for $g(x)$ in one dimension is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{poisson} \\tag{13}\n",
+ " -g''(x) = f(x)\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $f(x)$ is a given function for $x \\in (0,1)$.\n",
+ "\n",
+ "The conditions that $g(x)$ is chosen to fulfill, are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " g(0) &= 0 \\\\\n",
+ " g(1) &= 0\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.\n",
+ "The results from the networks can then be compared to the analytical solution.\n",
+ "In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.\n",
+ "\n",
+ "\n",
+ "Here, the function $g(x)$ to solve for follows the equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-g''(x) = f(x),\\qquad x \\in (0,1)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $f(x)$ is a given function, along with the chosen conditions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{aligned}\n",
+ "g(0) = g(1) = 0\n",
+ "\\end{aligned}\\label{cond} \\tag{14}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n",
+ "\n",
+ "For this case, a possible trial solution satisfying the conditions could be"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The analytical solution for this problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "g(x) = x(1 - x)\\exp(x)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad, elementwise_grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import pyplot as plt\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assumes input x being an one-dimensional array\n",
+ " num_values = np.size(x)\n",
+ " x = x.reshape(-1, num_values)\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ "\n",
+ " # Due to multiple hidden layers, define a variable referencing to the\n",
+ " # output of the previous layer:\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output\n",
+ "\n",
+ "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
+ " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
+ "\n",
+ " # Find the number of hidden layers:\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weigths and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 )\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " ## Start finding the optimal weigths using gradient descent\n",
+ "\n",
+ " # Find the Python function that represents the gradient of the cost function\n",
+ " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
+ " cost_function_deep_grad = grad(cost_function_deep,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " # Evaluate the gradient at the current weights and biases in P.\n",
+ " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
+ " # in the hidden layers and output layers evaluated at x.\n",
+ " cost_deep_grad = cost_function_deep_grad(P, x)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_deep_grad[l]\n",
+ "\n",
+ " print('Final cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "## Set up the cost function specified for this Poisson equation:\n",
+ "\n",
+ "# The right side of the ODE\n",
+ "def f(x):\n",
+ " return (3*x + x**2)*np.exp(x)\n",
+ "\n",
+ "def cost_function_deep(P, x):\n",
+ "\n",
+ " # Evaluate the trial function with the current parameters P\n",
+ " g_t = g_trial_deep(x,P)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the trial function\n",
+ " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n",
+ "\n",
+ " right_side = f(x)\n",
+ "\n",
+ " err_sqr = (-d2_g_t - right_side)**2\n",
+ " cost_sum = np.sum(err_sqr)\n",
+ "\n",
+ " return cost_sum/np.size(err_sqr)\n",
+ "\n",
+ "# The trial solution:\n",
+ "def g_trial_deep(x,P):\n",
+ " return x*(1-x)*deep_neural_network(P,x)\n",
+ "\n",
+ "# The analytic solution;\n",
+ "def g_analytic(x):\n",
+ " return x*(1-x)*np.exp(x)\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " npr.seed(4155)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nx = 10\n",
+ " x = np.linspace(0,1, Nx)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = [200,100]\n",
+ " num_iter = 1000\n",
+ " lmb = 1e-3\n",
+ "\n",
+ " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " g_dnn_ag = g_trial_deep(x,P)\n",
+ " g_analytical = g_analytic(x)\n",
+ "\n",
+ " # Find the maximum absolute difference between the solutons:\n",
+ " max_diff = np.max(np.abs(g_dnn_ag - g_analytical))\n",
+ " print(\"The max absolute difference between the solutions is: %g\"%max_diff)\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(x, g_analytical)\n",
+ " plt.plot(x, g_dnn_ag[0,:])\n",
+ " plt.legend(['analytical','nn'])\n",
+ " plt.xlabel('x')\n",
+ " plt.ylabel('g(x)')\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Comparing with a numerical scheme\n",
+ "\n",
+ "The Poisson equation is possible to solve using Taylor series to approximate the second derivative.\n",
+ "\n",
+ "Using Taylor series, the second derivative can be expressed as\n",
+ "\n",
+ "$$\n",
+ "g''(x) = \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2} + E_{\\Delta x}(x)\n",
+ "$$\n",
+ "\n",
+ "where $\\Delta x$ is a small step size and $E_{\\Delta x}(x)$ being the error term.\n",
+ "\n",
+ "Looking away from the error terms gives an approximation to the second derivative:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{approx} \\tag{15}\n",
+ "g''(x) \\approx \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If $x_i = i \\Delta x = x_{i-1} + \\Delta x$ and $g_i = g(x_i)$ for $i = 1,\\dots N_x - 2$ with $N_x$ being the number of values for $x$, ([15](#approx)) becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "g''(x_i) &\\approx \\frac{g(x_i + \\Delta x) - 2g(x_i) + g(x_i -\\Delta x)}{\\Delta x^2} \\\\\n",
+ "&= \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2}\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since we know from our problem that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "-g''(x) &= f(x) \\\\\n",
+ "&= (3x + x^2)\\exp(x)\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "along with the conditions $g(0) = g(1) = 0$,\n",
+ "the following scheme can be used to find an approximate solution for $g(x)$ numerically:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\begin{aligned}\n",
+ " -\\Big( \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2} \\Big) &= f(x_i) \\\\\n",
+ " -g_{i+1} + 2g_i - g_{i-1} &= \\Delta x^2 f(x_i)\n",
+ " \\end{aligned}\n",
+ "\\end{equation} \\label{odesys} \\tag{16}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for $i = 1, \\dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\\exp(x_i)$, which is given for our specific problem.\n",
+ "\n",
+ "The equation can be rewritten into a matrix equation:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{aligned}\n",
+ "\\begin{pmatrix}\n",
+ "2 & -1 & 0 & \\dots & 0 \\\\\n",
+ "-1 & 2 & -1 & \\dots & 0 \\\\\n",
+ "\\vdots & & \\ddots & & \\vdots \\\\\n",
+ "0 & \\dots & -1 & 2 & -1 \\\\\n",
+ "0 & \\dots & 0 & -1 & 2\\\\\n",
+ "\\end{pmatrix}\n",
+ "\\begin{pmatrix}\n",
+ "g_1 \\\\\n",
+ "g_2 \\\\\n",
+ "\\vdots \\\\\n",
+ "g_{N_x - 3} \\\\\n",
+ "g_{N_x - 2}\n",
+ "\\end{pmatrix}\n",
+ "&=\n",
+ "\\Delta x^2\n",
+ "\\begin{pmatrix}\n",
+ "f(x_1) \\\\\n",
+ "f(x_2) \\\\\n",
+ "\\vdots \\\\\n",
+ "f(x_{N_x - 3}) \\\\\n",
+ "f(x_{N_x - 2})\n",
+ "\\end{pmatrix} \\\\\n",
+ "\\boldsymbol{A}\\boldsymbol{g} &= \\boldsymbol{f},\n",
+ "\\end{aligned}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which makes it possible to solve for the vector $\\boldsymbol{g}$.\n",
+ "\n",
+ "\n",
+ "We can then compare the result from this numerical scheme with the output from our network using Autograd:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad, elementwise_grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import pyplot as plt\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assumes input x being an one-dimensional array\n",
+ " num_values = np.size(x)\n",
+ " x = x.reshape(-1, num_values)\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ "\n",
+ " # Due to multiple hidden layers, define a variable referencing to the\n",
+ " # output of the previous layer:\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output\n",
+ "\n",
+ "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n",
+ " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n",
+ "\n",
+ " # Find the number of hidden layers:\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weigths and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 )\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " ## Start finding the optimal weigths using gradient descent\n",
+ "\n",
+ " # Find the Python function that represents the gradient of the cost function\n",
+ " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n",
+ " cost_function_deep_grad = grad(cost_function_deep,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " # Evaluate the gradient at the current weights and biases in P.\n",
+ " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n",
+ " # in the hidden layers and output layers evaluated at x.\n",
+ " cost_deep_grad = cost_function_deep_grad(P, x)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_deep_grad[l]\n",
+ "\n",
+ " print('Final cost: %g'%cost_function_deep(P, x))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "## Set up the cost function specified for this Poisson equation:\n",
+ "\n",
+ "# The right side of the ODE\n",
+ "def f(x):\n",
+ " return (3*x + x**2)*np.exp(x)\n",
+ "\n",
+ "def cost_function_deep(P, x):\n",
+ "\n",
+ " # Evaluate the trial function with the current parameters P\n",
+ " g_t = g_trial_deep(x,P)\n",
+ "\n",
+ " # Find the derivative w.r.t x of the trial function\n",
+ " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n",
+ "\n",
+ " right_side = f(x)\n",
+ "\n",
+ " err_sqr = (-d2_g_t - right_side)**2\n",
+ " cost_sum = np.sum(err_sqr)\n",
+ "\n",
+ " return cost_sum/np.size(err_sqr)\n",
+ "\n",
+ "# The trial solution:\n",
+ "def g_trial_deep(x,P):\n",
+ " return x*(1-x)*deep_neural_network(P,x)\n",
+ "\n",
+ "# The analytic solution;\n",
+ "def g_analytic(x):\n",
+ " return x*(1-x)*np.exp(x)\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " npr.seed(4155)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nx = 10\n",
+ " x = np.linspace(0,1, Nx)\n",
+ "\n",
+ " ## Set up the initial parameters\n",
+ " num_hidden_neurons = [200,100]\n",
+ " num_iter = 1000\n",
+ " lmb = 1e-3\n",
+ "\n",
+ " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " g_dnn_ag = g_trial_deep(x,P)\n",
+ " g_analytical = g_analytic(x)\n",
+ "\n",
+ " # Find the maximum absolute difference between the solutons:\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n",
+ " plt.plot(x, g_analytical)\n",
+ " plt.plot(x, g_dnn_ag[0,:])\n",
+ " plt.legend(['analytical','nn'])\n",
+ " plt.xlabel('x')\n",
+ " plt.ylabel('g(x)')\n",
+ "\n",
+ " ## Perform the computation using the numerical scheme\n",
+ "\n",
+ " dx = 1/(Nx - 1)\n",
+ "\n",
+ " # Set up the matrix A\n",
+ " A = np.zeros((Nx-2,Nx-2))\n",
+ "\n",
+ " A[0,0] = 2\n",
+ " A[0,1] = -1\n",
+ "\n",
+ " for i in range(1,Nx-3):\n",
+ " A[i,i-1] = -1\n",
+ " A[i,i] = 2\n",
+ " A[i,i+1] = -1\n",
+ "\n",
+ " A[Nx - 3, Nx - 4] = -1\n",
+ " A[Nx - 3, Nx - 3] = 2\n",
+ "\n",
+ " # Set up the vector f\n",
+ " f_vec = dx**2 * f(x[1:-1])\n",
+ "\n",
+ " # Solve the equation\n",
+ " g_res = np.linalg.solve(A,f_vec)\n",
+ "\n",
+ " g_vec = np.zeros(Nx)\n",
+ " g_vec[1:-1] = g_res\n",
+ "\n",
+ " # Print the differences between each method\n",
+ " max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical))\n",
+ " max_diff2 = np.max(np.abs(g_vec - g_analytical))\n",
+ " print(\"The max absolute difference between the analytical solution and DNN Autograd: %g\"%max_diff1)\n",
+ " print(\"The max absolute difference between the analytical solution and numerical scheme: %g\"%max_diff2)\n",
+ "\n",
+ " # Plot the results\n",
+ " plt.figure(figsize=(10,10))\n",
+ "\n",
+ " plt.plot(x,g_vec)\n",
+ " plt.plot(x,g_analytical)\n",
+ " plt.plot(x,g_dnn_ag[0,:])\n",
+ "\n",
+ " plt.legend(['numerical scheme','analytical','dnn'])\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Partial Differential Equations\n",
+ "\n",
+ "A partial differential equation (PDE) has a solution here the function\n",
+ "is defined by multiple variables. The equation may involve all kinds\n",
+ "of combinations of which variables the function is differentiated with\n",
+ "respect to.\n",
+ "\n",
+ "In general, a partial differential equation for a function $g(x_1,\\dots,x_N)$ with $N$ variables may be expressed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{PDE} \\tag{17}\n",
+ " f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) = 0\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $f$ is an expression involving all kinds of possible mixed derivatives of $g(x_1,\\dots,x_N)$ up to an order $n$. In order for the solution to be unique, some additional conditions must also be given.\n",
+ "\n",
+ "### Type of problem\n",
+ "\n",
+ "The problem our network must solve for, is similar to the ODE case.\n",
+ "We must have a trial solution $g_t$ at hand.\n",
+ "\n",
+ "For instance, the trial solution could be expressed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " g_t(x_1,\\dots,x_N) = h_1(x_1,\\dots,x_N) + h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $h_1(x_1,\\dots,x_N)$ is a function that ensures $g_t(x_1,\\dots,x_N)$ satisfies some given conditions.\n",
+ "The neural network $N(x_1,\\dots,x_N,P)$ has weights and biases described by $P$ and $h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))$ is an expression using the output from the neural network in some way.\n",
+ "\n",
+ "The role of the function $h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))$, is to ensure that the output of $N(x_1,\\dots,x_N,P)$ is zero when $g_t(x_1,\\dots,x_N)$ is evaluated at the values of $x_1,\\dots,x_N$ where the given conditions must be satisfied. The function $h_1(x_1,\\dots,x_N)$ should alone make $g_t(x_1,\\dots,x_N)$ satisfy the conditions.\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Network requirements\n",
+ "\n",
+ "The network tries then the minimize the cost function following the\n",
+ "same ideas as described for the ODE case, but now with more than one\n",
+ "variables to consider. The concept still remains the same; find a set\n",
+ "of parameters $P$ such that the expression $f$ in ([17](#PDE)) is as\n",
+ "close to zero as possible.\n",
+ "\n",
+ "As for the ODE case, the cost function is the mean squared error that\n",
+ "the network must try to minimize. The cost function for the network to\n",
+ "minimize is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C\\left(x_1, \\dots, x_N, P\\right) = \\left( f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) \\right)^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we let $\\boldsymbol{x} = \\big( x_1, \\dots, x_N \\big)$ be an array containing the values for $x_1, \\dots, x_N$ respectively, the cost function can be reformulated into the following:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C\\left(\\boldsymbol{x}, P\\right) = f\\left( \\left( \\boldsymbol{x}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}) }{\\partial x_N^n} \\right) \\right)^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we also have $M$ different sets of values for $x_1, \\dots, x_N$, that is $\\boldsymbol{x}_i = \\big(x_1^{(i)}, \\dots, x_N^{(i)}\\big)$ for $i = 1,\\dots,M$ being the rows in matrix $X$, the cost function can be generalized into"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C\\left(X, P \\right) = \\sum_{i=1}^M f\\left( \\left( \\boldsymbol{x}_i, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}_i) }{\\partial x_N^n} \\right) \\right)^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Example: The diffusion equation\n",
+ "\n",
+ "In one spatial dimension, the equation reads"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where a possible choice of conditions are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n",
+ "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n",
+ "g(x,0) &= u(x),\\qquad x\\in [0,1]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $u(x)$ being some given function.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For this case, we want to find $g(x,t)$ such that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
+ "\\end{equation} \\label{diffonedim} \\tag{18}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n",
+ "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n",
+ "g(x,0) &= u(x),\\qquad x\\in [0,1]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $u(x) = \\sin(\\pi x)$.\n",
+ "\n",
+ "First, let us set up the deep neural network.\n",
+ "The deep neural network will follow the same structure as discussed in the examples solving the ODEs.\n",
+ "First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "The only change to do here, is to extend our network such that\n",
+ "functions of multiple parameters are correctly handled. In this case\n",
+ "we have two variables in our function to solve for, that is time $t$\n",
+ "and position $x$. The variables will be represented by a\n",
+ "one-dimensional array in the program. The program will evaluate the\n",
+ "network at each possible pair $(x,t)$, given an array for the desired\n",
+ "$x$-values and $t$-values to approximate the solution at."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # x is now a point and a 1D numpy array; make it a column vector\n",
+ " num_coordinates = np.size(x,0)\n",
+ " x = x.reshape(num_coordinates,-1)\n",
+ "\n",
+ " num_points = np.size(x,1)\n",
+ "\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output[0][0]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The cost function must then iterate through the given arrays\n",
+ "containing values for $x$ and $t$, defines a point $(x,t)$ the deep\n",
+ "neural network and the trial solution is evaluated at, and then finds\n",
+ "the Jacobian of the trial solution.\n",
+ "\n",
+ "A possible trial solution for this PDE is\n",
+ "\n",
+ "$$\n",
+ "g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)\n",
+ "$$\n",
+ "\n",
+ "with $A(x,t)$ being a function ensuring that $g_t(x,t)$ satisfies our given conditions, and $N(x,t,P)$ being the output from the deep neural network using weights and biases for each layer from $P$.\n",
+ "\n",
+ "To fulfill the conditions, $A(x,t)$ could be:\n",
+ "\n",
+ "$$\n",
+ "h_1(x,t) = (1-t)\\Big(u(x) - \\big((1-x)u(0) + x u(1)\\big)\\Big) = (1-t)u(x) = (1-t)\\sin(\\pi x)\n",
+ "$$\n",
+ "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The Jacobian is used because the program must find the derivative of\n",
+ "the trial solution with respect to $x$ and $t$.\n",
+ "\n",
+ "This gives the necessity of computing the Jacobian matrix, as we want\n",
+ "to evaluate the gradient with respect to $x$ and $t$ (note that the\n",
+ "Jacobian of a scalar-valued multivariate function is simply its\n",
+ "gradient).\n",
+ "\n",
+ "In Autograd, the differentiation is by default done with respect to\n",
+ "the first input argument of your Python function. Since the points is\n",
+ "an array representing $x$ and $t$, the Jacobian is calculated using\n",
+ "the values of $x$ and $t$.\n",
+ "\n",
+ "To find the second derivative with respect to $x$ and $t$, the\n",
+ "Jacobian can be found for the second time. The result is a Hessian\n",
+ "matrix, which is the matrix containing all the possible second order\n",
+ "mixed derivatives of $g(x,t)$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Set up the trial function:\n",
+ "def u(x):\n",
+ " return np.sin(np.pi*x)\n",
+ "\n",
+ "def g_trial(point,P):\n",
+ " x,t = point\n",
+ " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n",
+ "\n",
+ "# The right side of the ODE:\n",
+ "def f(point):\n",
+ " return 0.\n",
+ "\n",
+ "# The cost function:\n",
+ "def cost_function(P, x, t):\n",
+ " cost_sum = 0\n",
+ "\n",
+ " g_t_jacobian_func = jacobian(g_trial)\n",
+ " g_t_hessian_func = hessian(g_trial)\n",
+ "\n",
+ " for x_ in x:\n",
+ " for t_ in t:\n",
+ " point = np.array([x_,t_])\n",
+ "\n",
+ " g_t = g_trial(point,P)\n",
+ " g_t_jacobian = g_t_jacobian_func(point,P)\n",
+ " g_t_hessian = g_t_hessian_func(point,P)\n",
+ "\n",
+ " g_t_dt = g_t_jacobian[1]\n",
+ " g_t_d2x = g_t_hessian[0][0]\n",
+ "\n",
+ " func = f(point)\n",
+ "\n",
+ " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n",
+ " cost_sum += err_sqr\n",
+ "\n",
+ " return cost_sum"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Setting up the network using Autograd; The full program\n",
+ "\n",
+ "Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.\n",
+ "\n",
+ "The analytical solution of our problem is\n",
+ "\n",
+ "$$\n",
+ "g(x,t) = \\exp(-\\pi^2 t)\\sin(\\pi x)\n",
+ "$$\n",
+ "\n",
+ "A possible way to implement a neural network solving the PDE, is given below.\n",
+ "Be aware, though, that it is fairly slow for the parameters used.\n",
+ "A better result is possible, but requires more iterations, and thus longer time to complete.\n",
+ "\n",
+ "\n",
+ "Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.\n",
+ "Using TensorFlow results in a much better execution time. Try it!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import jacobian,hessian,grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import cm\n",
+ "from matplotlib import pyplot as plt\n",
+ "from mpl_toolkits.mplot3d import axes3d\n",
+ "\n",
+ "## Set up the network\n",
+ "\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # x is now a point and a 1D numpy array; make it a column vector\n",
+ " num_coordinates = np.size(x,0)\n",
+ " x = x.reshape(num_coordinates,-1)\n",
+ "\n",
+ " num_points = np.size(x,1)\n",
+ "\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output[0][0]\n",
+ "\n",
+ "## Define the trial solution and cost function\n",
+ "def u(x):\n",
+ " return np.sin(np.pi*x)\n",
+ "\n",
+ "def g_trial(point,P):\n",
+ " x,t = point\n",
+ " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n",
+ "\n",
+ "# The right side of the ODE:\n",
+ "def f(point):\n",
+ " return 0.\n",
+ "\n",
+ "# The cost function:\n",
+ "def cost_function(P, x, t):\n",
+ " cost_sum = 0\n",
+ "\n",
+ " g_t_jacobian_func = jacobian(g_trial)\n",
+ " g_t_hessian_func = hessian(g_trial)\n",
+ "\n",
+ " for x_ in x:\n",
+ " for t_ in t:\n",
+ " point = np.array([x_,t_])\n",
+ "\n",
+ " g_t = g_trial(point,P)\n",
+ " g_t_jacobian = g_t_jacobian_func(point,P)\n",
+ " g_t_hessian = g_t_hessian_func(point,P)\n",
+ "\n",
+ " g_t_dt = g_t_jacobian[1]\n",
+ " g_t_d2x = g_t_hessian[0][0]\n",
+ "\n",
+ " func = f(point)\n",
+ "\n",
+ " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n",
+ " cost_sum += err_sqr\n",
+ "\n",
+ " return cost_sum /( np.size(x)*np.size(t) )\n",
+ "\n",
+ "## For comparison, define the analytical solution\n",
+ "def g_analytic(point):\n",
+ " x,t = point\n",
+ " return np.exp(-np.pi**2*t)*np.sin(np.pi*x)\n",
+ "\n",
+ "## Set up a function for training the network to solve for the equation\n",
+ "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n",
+ " ## Set up initial weigths and biases\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weigths and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: ',cost_function(P, x, t))\n",
+ "\n",
+ " cost_function_grad = grad(cost_function,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " cost_grad = cost_function_grad(P, x , t)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_grad[l]\n",
+ "\n",
+ " print('Final cost: ',cost_function(P, x, t))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " ### Use the neural network:\n",
+ " npr.seed(15)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nx = 10; Nt = 10\n",
+ " x = np.linspace(0, 1, Nx)\n",
+ " t = np.linspace(0,1,Nt)\n",
+ "\n",
+ " ## Set up the parameters for the network\n",
+ " num_hidden_neurons = [100, 25]\n",
+ " num_iter = 250\n",
+ " lmb = 0.01\n",
+ "\n",
+ " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " ## Store the results\n",
+ " g_dnn_ag = np.zeros((Nx, Nt))\n",
+ " G_analytical = np.zeros((Nx, Nt))\n",
+ " for i,x_ in enumerate(x):\n",
+ " for j, t_ in enumerate(t):\n",
+ " point = np.array([x_, t_])\n",
+ " g_dnn_ag[i,j] = g_trial(point,P)\n",
+ "\n",
+ " G_analytical[i,j] = g_analytic(point)\n",
+ "\n",
+ " # Find the map difference between the analytical and the computed solution\n",
+ " diff_ag = np.abs(g_dnn_ag - G_analytical)\n",
+ " print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag))\n",
+ "\n",
+ " ## Plot the solutions in two dimensions, that being in position and time\n",
+ "\n",
+ " T,X = np.meshgrid(t,x)\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n",
+ " s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Analytical solution')\n",
+ " s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Difference')\n",
+ " s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ " ## Take some slices of the 3D plots just to see the solutions at particular times\n",
+ " indx1 = 0\n",
+ " indx2 = int(Nt/2)\n",
+ " indx3 = Nt-1\n",
+ "\n",
+ " t1 = t[indx1]\n",
+ " t2 = t[indx2]\n",
+ " t3 = t[indx3]\n",
+ "\n",
+ " # Slice the results from the DNN\n",
+ " res1 = g_dnn_ag[:,indx1]\n",
+ " res2 = g_dnn_ag[:,indx2]\n",
+ " res3 = g_dnn_ag[:,indx3]\n",
+ "\n",
+ " # Slice the analytical results\n",
+ " res_analytical1 = G_analytical[:,indx1]\n",
+ " res_analytical2 = G_analytical[:,indx2]\n",
+ " res_analytical3 = G_analytical[:,indx3]\n",
+ "\n",
+ " # Plot the slices\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t1)\n",
+ " plt.plot(x, res1)\n",
+ " plt.plot(x,res_analytical1)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t2)\n",
+ " plt.plot(x, res2)\n",
+ " plt.plot(x,res_analytical2)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t3)\n",
+ " plt.plot(x, res3)\n",
+ " plt.plot(x,res_analytical3)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Solving the wave equation with Neural Networks\n",
+ "\n",
+ "The wave equation is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $c$ being the specified wave speed.\n",
+ "\n",
+ "Here, the chosen conditions are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\tg(0,t) &= 0 \\\\\n",
+ "\tg(1,t) &= 0 \\\\\n",
+ "\tg(x,0) &= u(x) \\\\\n",
+ "\t\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0} &= v(x)\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0}$ means the derivative of $g(x,t)$ with respect to $t$ is evaluated at $t = 0$, and $u(x)$ and $v(x)$ being given functions.\n",
+ "\n",
+ "\n",
+ "The wave equation to solve for, is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \\label{wave} \\tag{19}\n",
+ "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2 \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $c$ is the given wave speed.\n",
+ "The chosen conditions for this equation are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{aligned}\n",
+ "g(0,t) &= 0, &t \\geq 0 \\\\\n",
+ "g(1,t) &= 0, &t \\geq 0 \\\\\n",
+ "g(x,0) &= u(x), &x\\in[0,1] \\\\\n",
+ "\\frac{\\partial g(x,t)}{\\partial t}\\Big |_{t = 0} &= v(x), &x \\in [0,1]\n",
+ "\\end{aligned} \\label{condwave} \\tag{20}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Setting up the network is done in similar matter as for the example of solving the diffusion equation.\n",
+ "The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.\n",
+ "\n",
+ "The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution $g_t(x,t)$ is\n",
+ "\n",
+ "$$\n",
+ "g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)\n",
+ "$$\n",
+ "\n",
+ "where\n",
+ "\n",
+ "$$\n",
+ "h_1(x,t) = (1-t^2)u(x) + tv(x)\n",
+ "$$\n",
+ "\n",
+ "Note that this trial solution satisfies the conditions only if $u(0) = v(0) = u(1) = v(1) = 0$, which is the case in this example.\n",
+ "\n",
+ "\n",
+ "The analytical solution for our specific problem, is\n",
+ "\n",
+ "$$\n",
+ "g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import hessian,grad\n",
+ "import autograd.numpy.random as npr\n",
+ "from matplotlib import cm\n",
+ "from matplotlib import pyplot as plt\n",
+ "from mpl_toolkits.mplot3d import axes3d\n",
+ "\n",
+ "## Set up the trial function:\n",
+ "def u(x):\n",
+ " return np.sin(np.pi*x)\n",
+ "\n",
+ "def v(x):\n",
+ " return -np.pi*np.sin(np.pi*x)\n",
+ "\n",
+ "def h1(point):\n",
+ " x,t = point\n",
+ " return (1 - t**2)*u(x) + t*v(x)\n",
+ "\n",
+ "def g_trial(point,P):\n",
+ " x,t = point\n",
+ " return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point)\n",
+ "\n",
+ "## Define the cost function\n",
+ "def cost_function(P, x, t):\n",
+ " cost_sum = 0\n",
+ "\n",
+ " g_t_hessian_func = hessian(g_trial)\n",
+ "\n",
+ " for x_ in x:\n",
+ " for t_ in t:\n",
+ " point = np.array([x_,t_])\n",
+ "\n",
+ " g_t_hessian = g_t_hessian_func(point,P)\n",
+ "\n",
+ " g_t_d2x = g_t_hessian[0][0]\n",
+ " g_t_d2t = g_t_hessian[1][1]\n",
+ "\n",
+ " err_sqr = ( (g_t_d2t - g_t_d2x) )**2\n",
+ " cost_sum += err_sqr\n",
+ "\n",
+ " return cost_sum / (np.size(t) * np.size(x))\n",
+ "\n",
+ "## The neural network\n",
+ "def sigmoid(z):\n",
+ " return 1/(1 + np.exp(-z))\n",
+ "\n",
+ "def deep_neural_network(deep_params, x):\n",
+ " # x is now a point and a 1D numpy array; make it a column vector\n",
+ " num_coordinates = np.size(x,0)\n",
+ " x = x.reshape(num_coordinates,-1)\n",
+ "\n",
+ " num_points = np.size(x,1)\n",
+ "\n",
+ " # N_hidden is the number of hidden layers\n",
+ " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n",
+ "\n",
+ " # Assume that the input layer does nothing to the input x\n",
+ " x_input = x\n",
+ " x_prev = x_input\n",
+ "\n",
+ " ## Hidden layers:\n",
+ "\n",
+ " for l in range(N_hidden):\n",
+ " # From the list of parameters P; find the correct weigths and bias for this layer\n",
+ " w_hidden = deep_params[l]\n",
+ "\n",
+ " # Add a row of ones to include bias\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n",
+ "\n",
+ " z_hidden = np.matmul(w_hidden, x_prev)\n",
+ " x_hidden = sigmoid(z_hidden)\n",
+ "\n",
+ " # Update x_prev such that next layer can use the output from this layer\n",
+ " x_prev = x_hidden\n",
+ "\n",
+ " ## Output layer:\n",
+ "\n",
+ " # Get the weights and bias for this layer\n",
+ " w_output = deep_params[-1]\n",
+ "\n",
+ " # Include bias:\n",
+ " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n",
+ "\n",
+ " z_output = np.matmul(w_output, x_prev)\n",
+ " x_output = z_output\n",
+ "\n",
+ " return x_output[0][0]\n",
+ "\n",
+ "## The analytical solution\n",
+ "def g_analytic(point):\n",
+ " x,t = point\n",
+ " return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t)\n",
+ "\n",
+ "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n",
+ " ## Set up initial weigths and biases\n",
+ " N_hidden = np.size(num_neurons)\n",
+ "\n",
+ " ## Set up initial weigths and biases\n",
+ "\n",
+ " # Initialize the list of parameters:\n",
+ " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n",
+ "\n",
+ " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n",
+ " for l in range(1,N_hidden):\n",
+ " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n",
+ "\n",
+ " # For the output layer\n",
+ " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n",
+ "\n",
+ " print('Initial cost: ',cost_function(P, x, t))\n",
+ "\n",
+ " cost_function_grad = grad(cost_function,0)\n",
+ "\n",
+ " # Let the update be done num_iter times\n",
+ " for i in range(num_iter):\n",
+ " cost_grad = cost_function_grad(P, x , t)\n",
+ "\n",
+ " for l in range(N_hidden+1):\n",
+ " P[l] = P[l] - lmb * cost_grad[l]\n",
+ "\n",
+ "\n",
+ " print('Final cost: ',cost_function(P, x, t))\n",
+ "\n",
+ " return P\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " ### Use the neural network:\n",
+ " npr.seed(15)\n",
+ "\n",
+ " ## Decide the vales of arguments to the function to solve\n",
+ " Nx = 10; Nt = 10\n",
+ " x = np.linspace(0, 1, Nx)\n",
+ " t = np.linspace(0,1,Nt)\n",
+ "\n",
+ " ## Set up the parameters for the network\n",
+ " num_hidden_neurons = [50,20]\n",
+ " num_iter = 1000\n",
+ " lmb = 0.01\n",
+ "\n",
+ " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n",
+ "\n",
+ " ## Store the results\n",
+ " res = np.zeros((Nx, Nt))\n",
+ " res_analytical = np.zeros((Nx, Nt))\n",
+ " for i,x_ in enumerate(x):\n",
+ " for j, t_ in enumerate(t):\n",
+ " point = np.array([x_, t_])\n",
+ " res[i,j] = g_trial(point,P)\n",
+ "\n",
+ " res_analytical[i,j] = g_analytic(point)\n",
+ "\n",
+ " diff = np.abs(res - res_analytical)\n",
+ " print(\"Max difference between analytical and solution from nn: %g\"%np.max(diff))\n",
+ "\n",
+ " ## Plot the solutions in two dimensions, that being in position and time\n",
+ "\n",
+ " T,X = np.meshgrid(t,x)\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n",
+ " s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Analytical solution')\n",
+ " s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ "\n",
+ " fig = plt.figure(figsize=(10,10))\n",
+ " ax = fig.gca(projection='3d')\n",
+ " ax.set_title('Difference')\n",
+ " s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis)\n",
+ " ax.set_xlabel('Time $t$')\n",
+ " ax.set_ylabel('Position $x$');\n",
+ "\n",
+ " ## Take some slices of the 3D plots just to see the solutions at particular times\n",
+ " indx1 = 0\n",
+ " indx2 = int(Nt/2)\n",
+ " indx3 = Nt-1\n",
+ "\n",
+ " t1 = t[indx1]\n",
+ " t2 = t[indx2]\n",
+ " t3 = t[indx3]\n",
+ "\n",
+ " # Slice the results from the DNN\n",
+ " res1 = res[:,indx1]\n",
+ " res2 = res[:,indx2]\n",
+ " res3 = res[:,indx3]\n",
+ "\n",
+ " # Slice the analytical results\n",
+ " res_analytical1 = res_analytical[:,indx1]\n",
+ " res_analytical2 = res_analytical[:,indx2]\n",
+ " res_analytical3 = res_analytical[:,indx3]\n",
+ "\n",
+ " # Plot the slices\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t1)\n",
+ " plt.plot(x, res1)\n",
+ " plt.plot(x,res_analytical1)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t2)\n",
+ " plt.plot(x, res2)\n",
+ " plt.plot(x,res_analytical2)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.figure(figsize=(10,10))\n",
+ " plt.title(\"Computed solutions at time = %g\"%t3)\n",
+ " plt.plot(x, res3)\n",
+ " plt.plot(x,res_analytical3)\n",
+ " plt.legend(['dnn','analytical'])\n",
+ "\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resources on differential equations and deep learning\n",
+ "\n",
+ "1. [Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al](https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf)\n",
+ "\n",
+ "2. [Neural networks for solving differential equations by A. Honchar](https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c)\n",
+ "\n",
+ "3. [Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener](http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf)\n",
+ "\n",
+ "4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter2.ipynb b/doc/LectureNotes/_build/html/_sources/chapter2.ipynb
new file mode 100644
index 000000000..fc1dc3fa0
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter2.ipynb
@@ -0,0 +1,4403 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Ridge and Lasso Regression\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Mathematical Interpretation of Ordinary Least Squares\n",
+ "\n",
+ "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n",
+ "\n",
+ "\n",
+ "We have shown that in ordinary least squares (OLS) the optimal parameters $\\beta$ are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n",
+ "\n",
+ "This means that our best model is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We now define a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a [projection matrix](https://en.wikipedia.org/wiki/Projection_matrix).\n",
+ "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We have defined the residual error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the matrix $\\boldsymbol{A}$ becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we have the obvious case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This serves also as a useful test of our codes. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The singular value decomposition\n",
+ "\n",
+ "\n",
+ "The examples we have looked at so far are cases where we normally can\n",
+ "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n",
+ "row vectors of the design matrix which are essentially orthogonal due\n",
+ "to the polynomial character of our model. Obtaining the inverse of the\n",
+ "design matrix is then often done via a so-called LU, QR or Cholesky\n",
+ "decomposition.\n",
+ "\n",
+ "\n",
+ "As we will also see in the first project, \n",
+ "this may\n",
+ "however not the be case in general and a standard matrix inversion\n",
+ "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "\n",
+ "There is however a way to circumvent this problem and also\n",
+ "gain some insights about the ordinary least squares approach, and\n",
+ "later shrinkage methods like Ridge and Lasso regressions.\n",
+ "\n",
+ "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n",
+ "perhaps the most powerful linear algebra algorithm. The SVD provides\n",
+ "a numerically stable matrix decomposition that is used in a large\n",
+ "swath oc applications and the decomposition is always stable\n",
+ "numerically.\n",
+ "\n",
+ "In machine learning it plays a central role in dealing with for\n",
+ "example design matrices that may be near singular or singular.\n",
+ "Furthermore, as we will see here, the singular values can be related\n",
+ "to the covariance matrix (and thereby the correlation matrix) and in\n",
+ "turn the variance of a given quantity. It plays also an important role\n",
+ "in the principal component analysis where high-dimensional data can be\n",
+ "reduced to the statistically relevant features.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "One of the typical problems we encounter with linear regression, in particular \n",
+ "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
+ "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
+ "may be linearly dependent, normally referred to as super-collinearity. \n",
+ "This means that the matrix may be rank deficient and it is basically impossible to \n",
+ "to model the data using linear regression. As an example, consider the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\mathbf{X} & = \\left[\n",
+ "\\begin{array}{rrr}\n",
+ "1 & -1 & 2\n",
+ "\\\\\n",
+ "1 & 0 & 1\n",
+ "\\\\\n",
+ "1 & 2 & -1\n",
+ "\\\\\n",
+ "1 & 1 & 0\n",
+ "\\end{array} \\right]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
+ "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
+ "the column rank) of a matrix is the dimension of the space spanned by the\n",
+ "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
+ "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "\n",
+ "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
+ "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{X} & = \\left[\n",
+ "\\begin{array}{rr}\n",
+ "1 & -1\n",
+ "\\\\\n",
+ "1 & -1\n",
+ "\\end{array} \\right].\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
+ "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "has linearly dependent column vectors, we will not be able to compute the inverse\n",
+ "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
+ "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
+ "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
+ "the regression parameters $\\beta_i$ cannot be estimated.\n",
+ "\n",
+ "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Basic math of the SVD\n",
+ "\n",
+ "\n",
+ "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
+ "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
+ "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
+ "The matrix has then a set of eigenpairs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the eigenvalues are given by the diagonal matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "\n",
+ "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\begin{bmatrix} \n",
+ "1& -1 \\\\\n",
+ "1& -1\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
+ "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "However, and this is the strength of the SVD algorithm, any general\n",
+ "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
+ "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
+ "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
+ "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
+ "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
+ "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
+ "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As an example, the above defective matrix can be decomposed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
+ "The SVD exits always! \n",
+ "\n",
+ "The SVD\n",
+ "decomposition (singular values) gives eigenvalues \n",
+ "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
+ "eigenvalues (singular values) are zero.\n",
+ "\n",
+ "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
+ "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
+ "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
+ "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
+ "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
+ "the rest of the matrix. There are at most $p$ singular values\n",
+ "assuming that $n > p$. In our regression examples for the nuclear\n",
+ "masses and the equation of state this is indeed the case, while for\n",
+ "the Ising model we have $p > n$. These are often cases that lead to\n",
+ "near singular or singular matrices.\n",
+ "\n",
+ "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ "\n",
+ "\n",
+ "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
+ "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
+ "irrelevant in our calculations since they are multiplied with the\n",
+ "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "\n",
+ "The economy-size decomposition removes extra rows or columns of zeros\n",
+ "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
+ "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
+ "Removing these zeros and columns can improve execution time\n",
+ "and reduce storage requirements without compromising the accuracy of\n",
+ "the decomposition.\n",
+ "\n",
+ "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
+ "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
+ "The $n=p$ case is obvious, we retain the full SVD. \n",
+ "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n",
+ "\n",
+ "## Codes for the SVD"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVD(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, S, VT = np.linalg.svd(A,full_matrices=True)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ " print(U)\n",
+ " print(S)\n",
+ " print(VT)\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " for i in range(0,len(VT)):\n",
+ " D[i,i]=S[i]\n",
+ " return U @ D @ VT\n",
+ "\n",
+ "\n",
+ "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n",
+ "#X = np.array([[1, 2], [3, 4], [5, 6]])\n",
+ "\n",
+ "print(X)\n",
+ "C = SVD(X)\n",
+ "# Print the difference between the original matrix and the SVD one\n",
+ "print(C-X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
+ "column is the row-wise sum of the other two columns. The rank of a\n",
+ "matrix (the column rank) is the dimension of space spanned by the\n",
+ "column vectors. The rank of the matrix is the number of linearly\n",
+ "independent columns, in this case just $2$. We see this from the\n",
+ "singular values when running the above code. Running the standard\n",
+ "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
+ "in the program terminating due to a singular matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n",
+ "cannot be multiplied directly.\n",
+ "\n",
+ "As you can see from the code, the $S$ vector must be converted into a\n",
+ "diagonal matrix. This may cause a problem as the size of the matrices\n",
+ "do not fit the rules of matrix multiplication, where the number of\n",
+ "columns in a matrix must match the number of rows in the subsequent\n",
+ "matrix.\n",
+ "\n",
+ "If you wish to include the zero singular values, you will need to\n",
+ "resize the matrices and set up a diagonal matrix as done in the above\n",
+ "example\n",
+ "\n",
+ "\n",
+ "## Code for SVD and Inversion of Matrices\n",
+ "\n",
+ "How do we use the SVD to invert a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is singular or near singular?\n",
+ "The simple answer is to use the linear algebra function for the pseudoinverse, that is"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "#Ainv = np.linlag.pinv(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ "\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " D = np.diag(s)\n",
+ " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
+ " return np.matmul(V,np.matmul(invD,UT))\n",
+ "\n",
+ "\n",
+ "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
+ "# Non-singular square matrix\n",
+ "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n",
+ "print(X)\n",
+ "A = np.transpose(X) @ X\n",
+ "# Brute force inversion\n",
+ "B = np.linalg.pinv(A) # here we could use np.linalg.inv(A), try it!\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(B-C))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n",
+ "\n",
+ "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n",
+ "rectangular matrices where the number of rows and columns are not equal.\n",
+ "\n",
+ "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n",
+ "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n",
+ "\n",
+ "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " # reciprocals of singular values of s\n",
+ " d = 1.0 / s\n",
+ " # create m x n D matrix\n",
+ " D = np.zeros(A.shape)\n",
+ " # populate D with n x n diagonal matrix\n",
+ " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n",
+ " UT = np.transpose(U)\n",
+ " V = np.transpose(VT)\n",
+ " return np.matmul(V,np.matmul(D.T,UT))\n",
+ "\n",
+ "\n",
+ "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n",
+ "print(A)\n",
+ "# Brute force inversion of super-collinear matrix\n",
+ "B = np.linalg.pinv(A)\n",
+ "print(B)\n",
+ "# Compare our own algorithm with pinv\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(C-B))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see from these examples, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Mathematics of the SVD and implications\n",
+ "\n",
+ "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n",
+ "\n",
+ "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can SVD decompose our matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n",
+ "\n",
+ "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n",
+ "\n",
+ "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All values beyond $p-1$ are all zero.\n",
+ "\n",
+ "\n",
+ "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "0 & 0 \\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n",
+ "\\boldsymbol{0}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "contains only the singular values. Note also (and we will use this below) that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is a $2\\times 2 $ matrix while"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 & 0\\\\\n",
+ "0 & 1 & 0\\\\\n",
+ "0 & 0 & 0\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n",
+ "contain only zeros. This will have important consequences for our SVD\n",
+ "decomposition of the design matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n",
+ "\n",
+ "This means, using the orthogonality of $\\boldsymbol{V}$, that we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using our SVD decomposition of $\\boldsymbol{X}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\tilde{\\boldsymbol{\\Sigma}}^{-2}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us, using the orthogonality of the matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_j\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{U}=[\\boldsymbol{u}_0,\\boldsymbol{u}_1,\\dots,\\boldsymbol{u}_{n-1}],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).\n",
+ "\n",
+ "It means that the ordinary least square model (with the optimal parameters) $\\boldsymbol{\\tilde{y}}$, corresponds to an orthogonal transformation of the output (or target) vector $\\boldsymbol{y}$ by the vectors of the matrix $\\boldsymbol{U}$.\n",
+ "\n",
+ "\n",
+ "## Further properties (important for our analyses later)\n",
+ "\n",
+ "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n",
+ "$n\\times p$ matrix. In most supervised learning cases we have that $n\n",
+ "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n",
+ "\n",
+ "In our lectures, the number of columns will\n",
+ "always refer to the number of features in our data set, while the\n",
+ "number of rows represents the number of data inputs. Note that in\n",
+ "other texts you may find the opposite notation. This has consequences\n",
+ "for the definition of for example the covariance matrix and its relation to the SVD.\n",
+ "\n",
+ "\n",
+ "## Meet the Covariance Matrix\n",
+ "\n",
+ "\n",
+ "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n",
+ "\n",
+ "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n",
+ "least squares is proportional to the second derivative of the cost\n",
+ "function, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "\n",
+ "The Hessian matrix plays an important role and is defined in this course as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Hessian matrix for ordinary least squares is also proportional to\n",
+ "the covariance matrix. This means also that we can use the SVD to find\n",
+ "the eigenvalues of the covariance matrix and the Hessian matrix in\n",
+ "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
+ "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n",
+ "\n",
+ "Suppose we have defined two vectors\n",
+ "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With this definition and recalling that the variance is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite the covariance matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Note:** we have used $1/n$ in the above definitions of the *sample* variance and covariance. We assume then that we can calculate the exact mean value. \n",
+ "What you will find in essentially all statistics texts are equations\n",
+ "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n",
+ "method corrects the bias in the estimation of the population variance\n",
+ "and covariance. It also partially corrects the bias in the estimation\n",
+ "of the population standard deviation. If you use a library like\n",
+ "**Scikit-Learn** or **nunmpy's** function calculate the covariance, this\n",
+ "quantity will be computed with a factor $1/(n-1)$.\n",
+ "\n",
+ "\n",
+ "The covariance takes values between zero and infinity and may thus\n",
+ "lead to problems with loss of numerical precision for particularly\n",
+ "large values. It is common to scale the covariance matrix by\n",
+ "introducing instead the correlation matrix defined via the so-called\n",
+ "correlation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
+ "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
+ "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
+ "and $\\boldsymbol{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example this is the function we constructed using **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
+ "we defined the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
+ "entries $n$ being the row elements.\n",
+ "We can rewrite the design/feature matrix in terms of its column vectors as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a given vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions, we can now rewrite our $2\\times 2$\n",
+ "correlation/covariance matrix in terms of a moe general design/feature\n",
+ "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
+ "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Numpy function **np.cov** calculates the covariance elements using\n",
+ "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
+ "the exact mean values. The following simple function uses the\n",
+ "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
+ "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n",
+ "\n",
+ "Note that this assumes you have the features as the rows, and the inputs as columns, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n",
+ " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
+ "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
+ "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "W = np.vstack((x, y))\n",
+ "C = np.cov(W)\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The previous example can be converted into the correlation matrix by\n",
+ "simply scaling the matrix elements with the variances. We should also\n",
+ "subtract the mean values for each column. This leads to the following\n",
+ "code which sets up the correlations matrix for the previous example in\n",
+ "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)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 100\n",
+ "# define two vectors \n",
+ "x = np.random.random(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "#scaling the x and y vectors \n",
+ "x = x - np.mean(x)\n",
+ "y = y - np.mean(y)\n",
+ "variance_x = np.sum(x@x)/n\n",
+ "variance_y = np.sum(y@y)/n\n",
+ "print(variance_x)\n",
+ "print(variance_y)\n",
+ "cov_xy = np.sum(x@y)/n\n",
+ "cov_xx = np.sum(x@x)/n\n",
+ "cov_yy = np.sum(y@y)/n\n",
+ "C = np.zeros((2,2))\n",
+ "C[0,0]= cov_xx/variance_x\n",
+ "C[1,1]= cov_yy/variance_y\n",
+ "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
+ "C[1,0]= C[0,1]\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that the matrix elements along the diagonal are one as they\n",
+ "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
+ "this matrix we easily see that it is a positive definite matrix.\n",
+ "\n",
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "x = x - np.mean(x)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "y = y - np.mean(y)\n",
+ "# Note that we transpose the matrix in order to stay with our ordering n x p\n",
+ "X = (np.vstack((x, y))).T\n",
+ "print(X)\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "print(Xpd)\n",
+ "correlation_matrix = Xpd.corr()\n",
+ "print(correlation_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We expand this model to the Franke function discussed earlier."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ "\treturn term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "def create_X(x, y, n ):\n",
+ "\tif len(x.shape) > 1:\n",
+ "\t\tx = np.ravel(x)\n",
+ "\t\ty = np.ravel(y)\n",
+ "\n",
+ "\tN = len(x)\n",
+ "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
+ "\tX = np.ones((N,l))\n",
+ "\n",
+ "\tfor i in range(1,n+1):\n",
+ "\t\tq = int((i)*(i+1)/2)\n",
+ "\t\tfor k in range(i+1):\n",
+ "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "\n",
+ "\treturn X\n",
+ "\n",
+ "\n",
+ "# Making meshgrid of datapoints and compute Franke's function\n",
+ "n = 4\n",
+ "N = 100\n",
+ "x = np.sort(np.random.uniform(0, 1, N))\n",
+ "y = np.sort(np.random.uniform(0, 1, N))\n",
+ "z = FrankeFunction(x, y)\n",
+ "X = create_X(x, y, n=n) \n",
+ "\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "# subtract the mean values and set up the covariance matrix\n",
+ "Xpd = Xpd - Xpd.mean()\n",
+ "covariance_matrix = Xpd.cov()\n",
+ "print(covariance_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note here that the covariance is zero for the first rows and\n",
+ "columns since all matrix elements in the design matrix were set to one\n",
+ "(we are fitting the function in terms of a polynomial of degree $n$).\n",
+ "\n",
+ "This means that the variance for these elements will be zero and will\n",
+ "cause problems when we set up the correlation matrix. We can simply\n",
+ "drop these elements and construct a correlation\n",
+ "matrix without these elements. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00} & x_{01}\\\\\n",
+ "x_{10} & x_{11}\\\\\n",
+ "\\end{bmatrix}=\\begin{bmatrix}\n",
+ "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n",
+ "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n",
+ "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "\n",
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Linking with the SVD\n",
+ "\n",
+ "We saw earlier that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n",
+ " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning we can write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n",
+ "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n",
+ "given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n",
+ "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n",
+ "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n",
+ "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n",
+ "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n",
+ "encode from the columns of $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Note that these are also the eigenvectors and eigenvalues of the\n",
+ "Hessian matrix.\n",
+ "\n",
+ "If we now recall the definition of the covariance matrix (not using\n",
+ "Bessel's correction) we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n",
+ "the number of samples) are the eigenvalues of the covariance\n",
+ "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n",
+ "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n",
+ "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n",
+ "absolute value of the eigenvalues of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $n\\times n$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n",
+ "the non-zero singular values plus now a series of zeros. The column\n",
+ "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n",
+ "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n",
+ "\n",
+ "Since we will mainly be interested in the correlations among the features\n",
+ "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n",
+ "values and the column vectors of $\\boldsymbol{V}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Ridge and Lasso Regression\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n",
+ "diagonal. In this case we have an equal number of rows and columns $n=p$.\n",
+ "\n",
+ "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Lasso regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n",
+ " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n",
+ "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$.\n",
+ "\n",
+ "\n",
+ "As another examples, \n",
+ "let us assume we have a data set with outputs/targets given by the vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and our inputs as a $3\\times 2$ design matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.\n",
+ "\n",
+ "\n",
+ "For ordinary least squares (OLS) we know that the optimal solution is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The code which implements this simpler case is presented after the discussion of Ridge and Lasso.\n",
+ "\n",
+ "\n",
+ "For Ridge regression we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n",
+ "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n",
+ "\n",
+ "To see this, let us write the cost function for Ridge regression. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We define the MSE without the $1/n$ factor and have then, using that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and taking the derivative with respect to $\\beta_0$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{8}{4+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and for $\\beta_1$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{2}{1+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$.\n",
+ "\n",
+ "\n",
+ "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n",
+ "and $\\beta_1$. This gives us the following derivatives of the cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n",
+ "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n",
+ "\n",
+ "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "4. $\\beta_0 < 0$ and $\\beta_1 < 0$.\n",
+ "\n",
+ "If we consider the first case, we have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-4(4-2\\beta_0)+\\lambda=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2(2-\\beta_1)+\\lambda=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yields"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{16+\\lambda}{8},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{4+\\lambda}{2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you.\n",
+ "\n",
+ "\n",
+ "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n",
+ "\n",
+ "First we study and compare the OLS and Ridge results. The next code compares all three methods.\n",
+ "We select values of the hyperparameter $\\lambda\\in [10^{-4},10^4]$ and compute the predicted values for ordinary least squares and Ridge regression."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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",
+ "\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",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ "# print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y,ypredictRidge)\n",
+ "# print(MSEPredict[i])\n",
+ " # Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see here that we reach a plateau for the Ridge results. Writing out the coefficients $\\boldsymbol{\\beta}$, we that they are getting smaller and smaller and our error stabilizes since the predicted values of $\\tilde{\\boldsymbol{y}}$ approach zero.\n",
+ "\n",
+ "This happens also for Lasso regression, as seen from the next code\n",
+ "output. The difference is that Lasso shrinks the values of $\\beta$ to\n",
+ "zero at a much earlier stage and the results flatten out. We see that\n",
+ "Lasso gives also an excellent fit for small values of $\\lambda$ and\n",
+ "shows rthe best performance of the three regression methods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn import linear_model\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",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ " print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSERidgePredict[i] = MSE(y,ypredictRidge)\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X,y)\n",
+ " ypredictLasso = RegLasso.predict(X)\n",
+ " print(RegLasso.coef_)\n",
+ " MSELassoPredict[i] = MSE(y,ypredictLasso)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We bring then back our exponential function example and study all\n",
+ "three regression methods. Depending on the level of noise, we note\n",
+ "that for small values of the hyperparameter $\\lambda$ all three\n",
+ "methods produce the same mean squared error. Again, Lasso shrinks the\n",
+ "parameter values to zero much earlier than Ridge regression and the\n",
+ "Lasso results flatten out much earlier since all $\\beta_j=0$ (check\n",
+ "this by printing the values). This case is an example of where OLS\n",
+ "performs best. Lasso and Ridge reproduce the OLS results for a limited\n",
+ "set of $\\lambda$ values."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "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 import linear_model\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",
+ "\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 MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Lasso and 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",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "MSELassoTrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, 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",
+ " # include lasso using Scikit-Learn\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " ytildeLasso = RegLasso.predict(X_train)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n",
+ "\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.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Both these example send a clear message. The addition of a\n",
+ "shrinkage/regularization term implies that we need to perform a search\n",
+ "for the optimal values of $\\lambda$. We will see this throughout these\n",
+ "series of lectures.\n",
+ "\n",
+ "\n",
+ "As a small addendum, we note that you can also solve this problem using the convex optimization package [CVXOPT](https://cvxopt.org/examples/mlbook/l1regls.html). This requires, in addition to having installed **CVXOPT**, you need to download the file *l1regl.py*.\n",
+ "The following code example solves the simpler problem we discussed above, where we have added the latter python file."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from cvxopt import matrix, spdiag, mul, div, sqrt, normal, setseed\n",
+ "from cvxopt import blas, lapack, solvers, sparse, spmatrix\n",
+ "import math\n",
+ "\n",
+ "try:\n",
+ " import mosek\n",
+ " import sys\n",
+ " __MOSEK = True\n",
+ "except: __MOSEK = False\n",
+ "\n",
+ "if __MOSEK:\n",
+ "\n",
+ " def l1regls_mosek(A, b):\n",
+ " \"\"\"\n",
+ "\n",
+ " Returns the solution of l1-norm regularized least-squares problem\n",
+ "\n",
+ " minimize || A*x - b ||_2^2 + e'*u\n",
+ "\n",
+ " subject to -u <= x <= u\n",
+ "\n",
+ " \"\"\"\n",
+ "\n",
+ " m, n = A.size\n",
+ "\n",
+ " env = mosek.Env()\n",
+ " task = env.Task(0,0)\n",
+ " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n",
+ "\n",
+ " task.appendvars( 2*n) # number of variables\n",
+ " task.appendcons( 2*n) # number of constraints\n",
+ "\n",
+ " # input quadratic objective\n",
+ " Q = matrix(0.0, (n,n)) \n",
+ " blas.syrk(A, Q, alpha = 2.0, trans='T')\n",
+ "\n",
+ " I = []\n",
+ " for i in range(n):\n",
+ " I.extend(range(i,n))\n",
+ "\n",
+ " J = []\n",
+ " for i in range(n):\n",
+ " J.extend((n-i)*[i])\n",
+ "\n",
+ " task.putqobj(I, J, list(Q[matrix(I) + matrix(J)*n]))\n",
+ " task.putclist(range(2*n), list(-2*A.T*b) + n*[1.0]) # setup linear objective\n",
+ "\n",
+ " # input constraint matrix row by row\n",
+ " for i in range(n):\n",
+ " task.putarow( i, [i, n+i], [1.0, -1.0])\n",
+ " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n",
+ "\n",
+ " # setup bounds on constraints\n",
+ " task.putboundslice(mosek.accmode.con,\n",
+ " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n",
+ " task.putboundslice(mosek.accmode.con,\n",
+ " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n",
+ "\n",
+ " # setup variable bounds\n",
+ " task.putboundslice(mosek.accmode.var,\n",
+ " 0, 2*n, 2*n*[mosek.boundkey.fr], 2*n*[0.0], 2*n*[0.0])\n",
+ "\n",
+ " # optimize the task\n",
+ " task.putobjsense(mosek.objsense.minimize)\n",
+ " task.optimize()\n",
+ " task.solutionsummary(mosek.streamtype.log)\n",
+ " x = n*[0.0]\n",
+ " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n",
+ "\n",
+ " return matrix(x)\n",
+ "\n",
+ " def l1regls_mosek2(A, b):\n",
+ " \"\"\"\n",
+ "\n",
+ " Returns the solution of l1-norm regularized least-squares problem\n",
+ "\n",
+ " minimize w'*w + e'*u\n",
+ "\n",
+ " subject to -u <= x <= u\n",
+ "\n",
+ " A*x - w = b\n",
+ "\n",
+ " \"\"\"\n",
+ "\n",
+ " m, n = A.size\n",
+ "\n",
+ " env = mosek.Env()\n",
+ " task = env.Task(0,0)\n",
+ " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n",
+ "\n",
+ " task.appendvars(2*n + m) # number of variables\n",
+ " task.appendcons(2*n + m) # number of constraints\n",
+ "\n",
+ " # input quadratic objective\n",
+ " task.putqobj(range(2*n,2*n+m), range(2*n,2*n+m), m*[2.0])\n",
+ "\n",
+ " task.putclist(range(2*n+m), n*[0.0] + n*[1.0] + m*[0.0]) # setup linear objective\n",
+ "\n",
+ " # input constraint matrix row by row\n",
+ " for i in range(n):\n",
+ " task.putarow( i, [i, n+i], [1.0, -1.0])\n",
+ " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n",
+ "\n",
+ " for i in range(m):\n",
+ " task.putarow( 2*n+i, range(n) + [2*n+i], list(A[i,:]) + [-1.0])\n",
+ "\n",
+ " # setup bounds on constraints\n",
+ " task.putboundslice(mosek.accmode.con,\n",
+ " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n",
+ " task.putboundslice(mosek.accmode.con,\n",
+ " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n",
+ " task.putboundslice(mosek.accmode.con,\n",
+ " 2*n, 2*n+m, m*[mosek.boundkey.fx], list(b), list(b))\n",
+ "\n",
+ " # setup variable bounds\n",
+ " task.putboundslice(mosek.accmode.var, 0, 2*n+m, (2*n+m)*[mosek.boundkey.fr], \n",
+ " (2*n+m)*[0.0], (2*n+m)*[0.0])\n",
+ "\n",
+ " # optimize the task\n",
+ " task.putobjsense(mosek.objsense.minimize)\n",
+ " task.optimize()\n",
+ " task.solutionsummary(mosek.streamtype.log)\n",
+ " x = n*[0.0]\n",
+ " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n",
+ "\n",
+ " return matrix(x)\n",
+ "\n",
+ "def l1regls(A, b):\n",
+ " \"\"\"\n",
+ " \n",
+ " Returns the solution of l1-norm regularized least-squares problem\n",
+ " \n",
+ " minimize || A*x - b ||_2^2 + || x ||_1.\n",
+ "\n",
+ " \"\"\"\n",
+ "\n",
+ " m, n = A.size\n",
+ " q = matrix(1.0, (2*n,1))\n",
+ " q[:n] = -2.0 * A.T * b\n",
+ "\n",
+ " def P(u, v, alpha = 1.0, beta = 0.0 ):\n",
+ " \"\"\"\n",
+ " v := alpha * 2.0 * [ A'*A, 0; 0, 0 ] * u + beta * v \n",
+ " \"\"\"\n",
+ " v *= beta\n",
+ " v[:n] += alpha * 2.0 * A.T * (A * u[:n])\n",
+ "\n",
+ "\n",
+ " def G(u, v, alpha=1.0, beta=0.0, trans='N'):\n",
+ " \"\"\"\n",
+ " v := alpha*[I, -I; -I, -I] * u + beta * v (trans = 'N' or 'T')\n",
+ " \"\"\"\n",
+ "\n",
+ " v *= beta\n",
+ " v[:n] += alpha*(u[:n] - u[n:])\n",
+ " v[n:] += alpha*(-u[:n] - u[n:])\n",
+ "\n",
+ " h = matrix(0.0, (2*n,1))\n",
+ "\n",
+ "\n",
+ " # Customized solver for the KKT system \n",
+ " #\n",
+ " # [ 2.0*A'*A 0 I -I ] [x[:n] ] [bx[:n] ]\n",
+ " # [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ].\n",
+ " # [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]]\n",
+ " # [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]]\n",
+ " #\n",
+ " # where D1 = W['di'][:n]**2, D2 = W['di'][:n]**2.\n",
+ " # \n",
+ " # We first eliminate zl and x[n:]:\n",
+ " #\n",
+ " # ( 2*A'*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = \n",
+ " # bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + \n",
+ " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n",
+ " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] \n",
+ " #\n",
+ " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n",
+ " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n",
+ " #\n",
+ " # zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] )\n",
+ " # zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ).\n",
+ " #\n",
+ " # The first equation has the form\n",
+ " #\n",
+ " # (A'*A + D)*x[:n] = rhs\n",
+ " #\n",
+ " # and is equivalent to\n",
+ " #\n",
+ " # [ D A' ] [ x:n] ] = [ rhs ]\n",
+ " # [ A -I ] [ v ] [ 0 ].\n",
+ " #\n",
+ " # It can be solved as \n",
+ " #\n",
+ " # ( A*D^-1*A' + I ) * v = A * D^-1 * rhs\n",
+ " # x[:n] = D^-1 * ( rhs - A'*v ).\n",
+ "\n",
+ " S = matrix(0.0, (m,m))\n",
+ " Asc = matrix(0.0, (m,n))\n",
+ " v = matrix(0.0, (m,1))\n",
+ "\n",
+ " def Fkkt(W):\n",
+ "\n",
+ " # Factor \n",
+ " #\n",
+ " # S = A*D^-1*A' + I \n",
+ " #\n",
+ " # where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2.\n",
+ "\n",
+ " d1, d2 = W['di'][:n]**2, W['di'][n:]**2\n",
+ "\n",
+ " # ds is square root of diagonal of D\n",
+ " ds = math.sqrt(2.0) * div( mul( W['di'][:n], W['di'][n:]), \n",
+ " sqrt(d1+d2) )\n",
+ " d3 = div(d2 - d1, d1 + d2)\n",
+ " \n",
+ " # Asc = A*diag(d)^-1/2\n",
+ " Asc = A * spdiag(ds**-1)\n",
+ "\n",
+ " # S = I + A * D^-1 * A'\n",
+ " blas.syrk(Asc, S)\n",
+ " S[::m+1] += 1.0 \n",
+ " lapack.potrf(S)\n",
+ "\n",
+ " def g(x, y, z):\n",
+ "\n",
+ " x[:n] = 0.5 * ( x[:n] - mul(d3, x[n:]) + \n",
+ " mul(d1, z[:n] + mul(d3, z[:n])) - mul(d2, z[n:] - \n",
+ " mul(d3, z[n:])) )\n",
+ " x[:n] = div( x[:n], ds) \n",
+ "\n",
+ " # Solve\n",
+ " #\n",
+ " # S * v = 0.5 * A * D^-1 * ( bx[:n] - \n",
+ " # (D2-D1)*(D1+D2)^-1 * bx[n:] + \n",
+ " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n",
+ " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] )\n",
+ " \n",
+ " blas.gemv(Asc, x, v)\n",
+ " lapack.potrs(S, v)\n",
+ " \n",
+ " # x[:n] = D^-1 * ( rhs - A'*v ).\n",
+ " blas.gemv(Asc, v, x, alpha=-1.0, beta=1.0, trans='T')\n",
+ " x[:n] = div(x[:n], ds)\n",
+ "\n",
+ " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n",
+ " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n",
+ " x[n:] = div( x[n:] - mul(d1, z[:n]) - mul(d2, z[n:]), d1+d2 )\\\n",
+ " - mul( d3, x[:n] )\n",
+ " \n",
+ " # zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] )\n",
+ " # zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ).\n",
+ " z[:n] = mul( W['di'][:n], x[:n] - x[n:] - z[:n] ) \n",
+ " z[n:] = mul( W['di'][n:], -x[:n] - x[n:] - z[n:] ) \n",
+ "\n",
+ " return g\n",
+ "\n",
+ " return solvers.coneqp(P, q, G, h, kktsolver = Fkkt)['x'][:n]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then we call the above functions and solve the problem, as done here"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from cvxopt import matrix, normal\n",
+ "\n",
+ "X = matrix( [ [ 2, 0, 1], [0, 1, 3]])\n",
+ "y = matrix( [4, 2, 3])\n",
+ "x = l1regls(X,y)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**More text will be added to this example.**\n",
+ "\n",
+ "## Linking the regression analysis with a statistical interpretation\n",
+ "\n",
+ "We will now couple the discussions of ordinary least squares, Ridge\n",
+ "and Lasso regression with a statistical interpretation, that is we\n",
+ "move from a linear algebra analysis to a statistical analysis. In\n",
+ "particular, we will focus on what the regularization terms can result\n",
+ "in. We will amongst other things show that the regularization\n",
+ "parameter can reduce considerably the variance of the parameters\n",
+ "$\\beta$.\n",
+ "\n",
+ "\n",
+ "The\n",
+ "advantage of doing linear regression is that we actually end up with\n",
+ "analytical expressions for several statistical quantities. \n",
+ "Standard least squares and Ridge regression allow us to\n",
+ "derive quantities like the variance and other expectation values in a\n",
+ "rather straightforward way.\n",
+ "\n",
+ "\n",
+ "It is assumed that $\\varepsilon_i\n",
+ "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
+ "independent, i.e.:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mbox{Cov}(\\varepsilon_{i_1},\n",
+ "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
+ "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The randomness of $\\varepsilon_i$ implies that\n",
+ "$\\mathbf{y}_i$ is also a random variable. In particular,\n",
+ "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
+ "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n",
+ "non-random scalar. To specify the parameters of the distribution of\n",
+ "$\\mathbf{y}_i$ we need to calculate its first two moments. \n",
+ "\n",
+ "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n",
+ "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n",
+ "row number $i$ and perform a sum over all values $p$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
+ "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
+ "which describe our data"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We approximate this function with our model from the solution of the linear regression equations, that is our\n",
+ "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mathbb{E}(y_i) & =\n",
+ "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n",
+ "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "while\n",
+ "its variance is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n",
+ "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n",
+ "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
+ "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n",
+ "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n",
+ "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
+ "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n",
+ "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n",
+ "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n",
+ "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
+ "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
+ "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n",
+ "\n",
+ "\n",
+ "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means that the estimator of the regression parameters is unbiased.\n",
+ "\n",
+ "We can also calculate the variance\n",
+ "\n",
+ "The variance of $\\boldsymbol{\\beta}$ is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{eqnarray*}\n",
+ "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n",
+ "\\\\\n",
+ "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n",
+ "\\\\\n",
+ "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n",
+ "% \\\\\n",
+ "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n",
+ "\\\\\n",
+ "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n",
+ "\\end{eqnarray*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n",
+ "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n",
+ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
+ "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
+ "variance of the estimate of the $j$-th regression coefficient:\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n",
+ "construct a confidence interval for the estimates.\n",
+ "\n",
+ "\n",
+ "In a similar way, we can obtain analytical expressions for say the\n",
+ "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n",
+ "when we employ Ridge regression, allowing us again to define a confidence interval. \n",
+ "\n",
+ "It is rather straightforward to show that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see clearly that \n",
+ "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n",
+ "\n",
+ "We can also compute the variance as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n",
+ "\n",
+ "With this, we can compute the difference"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The difference is non-negative definite since each component of the\n",
+ "matrix product is non-negative definite. \n",
+ "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Deriving OLS from a probability distribution\n",
+ "\n",
+ "Our basic assumption when we derived the OLS equations was to assume\n",
+ "that our output is determined by a given continuous function\n",
+ "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
+ "distribution with zero mean value and an undetermined variance\n",
+ "$\\sigma^2$.\n",
+ "\n",
+ "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
+ "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
+ "the design matrix are not stochastic variables, we can assume that the\n",
+ "probability distribution of our targets is also a normal distribution\n",
+ "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
+ "single output $y_i$ is given by the Gaussian distribution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
+ "We define this distribution as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
+ "\n",
+ "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
+ "in case we have a simple one-dimensional input and output case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
+ "We can now rewrite the above probability as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is a conditional probability (see below) and reads as the\n",
+ "likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters\n",
+ "$\\boldsymbol{\\beta}$.\n",
+ "\n",
+ "\n",
+ "In statistics, maximum likelihood estimation (MLE) is a method of\n",
+ "estimating the parameters of an assumed probability distribution,\n",
+ "given some observed data. This is achieved by maximizing a likelihood\n",
+ "function so that, under the assumed statistical model, the observed\n",
+ "data is the most probable. \n",
+ "\n",
+ "\n",
+ "We will assume here that our events are given by the above Gaussian\n",
+ "distribution and we will determine the optimal parameters $\\beta$ by\n",
+ "maximizing the above PDF. However, computing the derivatives of a\n",
+ "product function is cumbersome and can easily lead to overflow and/or\n",
+ "underflowproblems, with potentials for loss of numerical precision.\n",
+ "\n",
+ "\n",
+ "In practice, it is more convenient to maximize the logarithm of the\n",
+ "PDF because it is a monotonically increasing function of the argument.\n",
+ "Alternatively, and this will be our option, we will minimize the\n",
+ "negative of the logarithm since this is a monotonically decreasing\n",
+ "function.\n",
+ "\n",
+ "Note also that maximization/minimization of the logarithm of the PDF\n",
+ "is equivalent to the maximization/minimization of the function itself.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the well-known OLS equation for the optimal paramters $\\beta$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. \n",
+ "\n",
+ "\n",
+ "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n",
+ "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n",
+ "\n",
+ "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n",
+ "\n",
+ "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n",
+ "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n",
+ "\n",
+ "The union of events is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The product rule (aka joint probability) is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n",
+ "\n",
+ "If we have independent events then $p(X,Y)=p(X)p(Y)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conditional probability, if $p(Y) > 0$, is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we combine the conditional probability with the marginal probability and the standard product rule, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we can rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
+ "\n",
+ "\n",
+ "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
+ "evaluated for the observed data $Y$ and can be viewed as a function of\n",
+ "the parameter space represented by $X$. This function is not\n",
+ "necesseraly normalized and is normally called the likelihood function.\n",
+ "\n",
+ "The function $p(X)$ on the right hand side is called the prior while\n",
+ "the function on the left hand side is the called the posterior\n",
+ "probability. The denominator on the right hand side serves as a\n",
+ "normalization factor for the posterior distribution.\n",
+ "\n",
+ "Let us try to illustrate Bayes' theorem through an example.\n",
+ "\n",
+ "\n",
+ "Let us suppose that you are undergoing a series of mammography scans\n",
+ "in order to rule out possible breast cancer cases. We define the\n",
+ "sensitivity for a positive event by the variable $X$. It takes binary\n",
+ "values with $X=1$ representing a positive event and $X=0$ being a\n",
+ "negative event. We reserve $Y$ as a classification parameter for\n",
+ "either a negative or a positive breast cancer confirmation. (Short\n",
+ "note on wordings: positive here means having breast cancer, although\n",
+ "none of us would consider this being a positive thing).\n",
+ "\n",
+ "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n",
+ "\n",
+ "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$ (the numbers here are all made up),\n",
+ "that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=1) =0.8.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This obviously sounds scary since many would conclude that if the test\n",
+ "is positive, there is a likelihood of $80\\%$ for having cancer. It is\n",
+ "however not correct, as the following Bayesian analysis shows. The correct question to pose is *what is the probability of having breast cancer in case of a positive test?*\n",
+ "We are thus interested in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1\\vert X=1),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "instead of $p(X=1\\vert Y=1)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we look at various national surveys on breast cancer, the general\n",
+ "likelihood of developing breast cancer is a very small number. Let us\n",
+ "assume that the prior probability in the population as a whole is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1) =0.004.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need also to account for the fact that the test may produce a false\n",
+ "positive result (false alarm). Let us here assume that we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=0) =0.1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using Bayes' theorem we can then find the posterior probability that\n",
+ "the person has breast cancer in case of a positive test, that is we\n",
+ "can compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}= \n",
+ "\\label{_auto2} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ " \\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n",
+ "\\label{_auto3} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Bayes' Theorem and Ridge and Lasso Regression\n",
+ "\n",
+ "Hitherto we have discussed Ridge and Lasso regression in terms of a\n",
+ "linear analysis. This may to many of you feel rather technical and\n",
+ "perhaps not that intuitive. The question is whether we can develop a\n",
+ "more intuitive way of understanding what Ridge and Lasso express.\n",
+ "\n",
+ "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n",
+ "\n",
+ "\n",
+ "We will play around with a study of the values for the optimal\n",
+ "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
+ "OLS, you will notice as function of the noise and polynomial degree,\n",
+ "that the parameters $\\beta$ will fluctuate from order to order in the\n",
+ "polynomial fit and that for larger and larger polynomial degrees of\n",
+ "freedom, the parameters will tend to increase in value for OLS.\n",
+ "\n",
+ "For Ridge and Lasso regression, the higher order parameters will\n",
+ "typically be reduced, providing thereby less fluctuations from one\n",
+ "order to another one."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\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",
+ "# Make data set.\n",
+ "n = 10000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
+ "\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = x**(degree)\n",
+ "\n",
+ "\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",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 4\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-3, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge and Lasso\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " # Compute the MSE and print it\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ "# print(lmb,RegRidge.coef_)\n",
+ "# print(lmb,RegLasso.coef_)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How can we understand this?\n",
+ "\n",
+ "Let us write out the values of the coefficients $\\beta_i$ as functions\n",
+ "of the polynomial degree and noise. We will focus only on the Ridge\n",
+ "results and some few selected values of the hyperparameter $\\lambda$.\n",
+ "\n",
+ "If we don't include any noise and run this code for different values\n",
+ "of the polynomial degree, we notice that the results for $\\beta_i$ do\n",
+ "not show great changes from one order to the next. This is an\n",
+ "indication that for higher polynomial orders, our parameters become\n",
+ "less important.\n",
+ "\n",
+ "If we however add noise, what happens is that the polynomial fit is\n",
+ "trying to adjust the fit to traverse in the best possible way all data\n",
+ "points. This can lead to large fluctuations in the parameters\n",
+ "$\\beta_i$ as functions of polynomial order. It will also be reflected\n",
+ "in a larger value of the variance of each parameter $\\beta_i$. What\n",
+ "Ridge regression (and Lasso as well) are doing then is to try to\n",
+ "quench the fluctuations in the parameters of $\\beta_i$ which have a\n",
+ "large variance (normally for higher orders in the polynomial)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "from IPython.display import display\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "# Make data set.\n",
+ "n = 1000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
+ "\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = x**(degree)\n",
+ "\n",
+ "\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",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 5\n",
+ "lambdas = np.logspace(-3, 2, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge only\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " Coeffs = np.array(RegRidge.coef_)\n",
+ " BetaValues = pd.DataFrame(Coeffs)\n",
+ " BetaValues.columns = ['beta']\n",
+ " display(BetaValues)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As an exercise, repeat these calculations with ordinary least squares\n",
+ "only with and without noise. Calculate thereafter the variance of the\n",
+ "parameters $\\beta_j$ as function of polynomial order and of the added\n",
+ "noise. Here we recommend to use $\\sigma^2=1$ as variance for the\n",
+ "added noise (which follows a normal distribution with mean value zero).\n",
+ "Comment your results. If you have a large noise term, do the parameters $\\beta_j$ vary more as function\n",
+ "model complexity? And what about their variance? \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Linking Bayes' Theorem with Ridge and Lasso Regression\n",
+ "\n",
+ "We have seen that Ridge regression suppresses those features which\n",
+ "have a small singular value. This corresponds to a feature which exhibits\n",
+ "a large variance in the parameters $\\beta_j$.\n",
+ "Our analysis hitherto has been based on linear algebra. To add to our intuition, we will use\n",
+ "Bayes' theorem in order to deepen our understanding of Ridge and Lasso regression. \n",
+ "\n",
+ "For ordinary least squares we postulated that the maximum likelihood for the domain of events $\\boldsymbol{D}$ (one-dimensional case)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
+ "\n",
+ "\n",
+ "\n",
+ "With the posterior probability defined by a likelihood which we have\n",
+ "already modeled and an unknown prior, we are now ready to make\n",
+ "additional models for the prior.\n",
+ "\n",
+ "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and\n",
+ "the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is\n",
+ "given by a Gaussian with mean value zero and variance $\\tau^2$, that\n",
+ "is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
+ "did for OLS, this is most conveniently done by taking the negative\n",
+ "logarithm of the posterior probability. Doing so and leaving out the\n",
+ "terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/2\\tau^2$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Ridge cost function! Nice, isn't it?\n",
+ "\n",
+ "\n",
+ "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the negative\n",
+ "logarithm of the posterior probability and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/\\tau$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Lasso cost function! \n",
+ "\n",
+ "\n",
+ "Plotting these prior functions shows us that we can use the parameter\n",
+ "$\\lambda$ to shrink or increase the role of a given parameter\n",
+ "$\\beta_j$. The variance for the Laplace distribution is\n",
+ "$2\\tau^2=1/\\lambda$ while for the Gaussian distribution it is\n",
+ "$\\sigma^2=1/(2\\lambda)$. Thus, increasing the variance means\n",
+ "decreasing $\\lambda$ and shrinking the variance means increasing\n",
+ "$\\lamdbda$. When we increase $\\lambda$, this corresponds to shrinking the role of less important features (small singular values)."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter3.ipynb b/doc/LectureNotes/_build/html/_sources/chapter3.ipynb
new file mode 100644
index 000000000..7cb02906e
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter3.ipynb
@@ -0,0 +1,3565 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Resampling Methods\n",
+ "\n",
+ "## Introduction\n",
+ "\n",
+ "Resampling methods are an indispensable tool in modern\n",
+ "statistics. They involve repeatedly drawing samples from a training\n",
+ "set and refitting a model of interest on each sample in order to\n",
+ "obtain additional information about the fitted model. For example, in\n",
+ "order to estimate the variability of a linear regression fit, we can\n",
+ "repeatedly draw different samples from the training data, fit a linear\n",
+ "regression to each new sample, and then examine the extent to which\n",
+ "the resulting fits differ. Such an approach may allow us to obtain\n",
+ "information that would not be available from fitting the model only\n",
+ "once using the original training sample.\n",
+ "\n",
+ "Two resampling methods are often used in Machine Learning analyses,\n",
+ "1. The **bootstrap method**\n",
+ "\n",
+ "2. and **Cross-Validation**\n",
+ "\n",
+ "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
+ "cross-validation and the bootstrap method. \n",
+ "\n",
+ "\n",
+ "Resampling approaches can be computationally expensive, because they\n",
+ "involve fitting the same statistical method multiple times using\n",
+ "different subsets of the training data. However, due to recent\n",
+ "advances in computing power, the computational requirements of\n",
+ "resampling methods generally are not prohibitive. In this chapter, we\n",
+ "discuss two of the most commonly used resampling methods,\n",
+ "cross-validation and the bootstrap. Both methods are important tools\n",
+ "in the practical application of many statistical learning\n",
+ "procedures. For example, cross-validation can be used to estimate the\n",
+ "test error associated with a given statistical learning method in\n",
+ "order to evaluate its performance, or to select the appropriate level\n",
+ "of flexibility. The process of evaluating a model’s performance is\n",
+ "known as model assessment, whereas the process of selecting the proper\n",
+ "level of flexibility for a model is known as model selection. The\n",
+ "bootstrap is widely used.\n",
+ "\n",
+ "\n",
+ "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
+ "\n",
+ "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
+ "\n",
+ "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
+ "\n",
+ "## Reminder on Statistics\n",
+ "\n",
+ "\n",
+ "* As in other experiments, many numerical experiments have two classes of errors:\n",
+ "\n",
+ " * Statistical errors\n",
+ "\n",
+ " * Systematical errors\n",
+ "\n",
+ "\n",
+ "* Statistical errors can be estimated using standard tools from statistics\n",
+ "\n",
+ "* Systematical errors are method specific and must be treated differently from case to case. \n",
+ "\n",
+ "The\n",
+ "advantage of doing linear regression is that we actually end up with\n",
+ "analytical expressions for several statistical quantities. \n",
+ "Standard least squares and Ridge regression allow us to\n",
+ "derive quantities like the variance and other expectation values in a\n",
+ "rather straightforward way.\n",
+ "\n",
+ "\n",
+ "It is assumed that $\\varepsilon_i\n",
+ "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
+ "independent, i.e.:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mbox{Cov}(\\varepsilon_{i_1},\n",
+ "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
+ "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The randomness of $\\varepsilon_i$ implies that\n",
+ "$\\mathbf{y}_i$ is also a random variable. In particular,\n",
+ "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
+ "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n",
+ "non-random scalar. To specify the parameters of the distribution of\n",
+ "$\\mathbf{y}_i$ we need to calculate its first two moments. \n",
+ "\n",
+ "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n",
+ "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n",
+ "row number $i$ and perform a sum over all values $p$.\n",
+ "\n",
+ "\n",
+ "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
+ "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
+ "which describe our data"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We approximate this function with our model from the solution of the linear regression equations, that is our\n",
+ "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mathbb{E}(y_i) & =\n",
+ "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n",
+ "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "while\n",
+ "its variance is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n",
+ "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n",
+ "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
+ "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n",
+ "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n",
+ "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
+ "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n",
+ "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n",
+ "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n",
+ "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
+ "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
+ "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n",
+ "\n",
+ "\n",
+ "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means that the estimator of the regression parameters is unbiased.\n",
+ "v\n",
+ "We can also calculate the variance\n",
+ "\n",
+ "The variance of $\\boldsymbol{\\beta}$ is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{eqnarray*}\n",
+ "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n",
+ "\\\\\n",
+ "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n",
+ "\\\\\n",
+ "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n",
+ "% \\\\\n",
+ "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n",
+ "\\\\\n",
+ "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n",
+ "\\end{eqnarray*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n",
+ "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n",
+ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
+ "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
+ "variance of the estimate of the $j$-th regression coefficient:\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
+ "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "construct a confidence interval for the estimates.\n",
+ "\n",
+ "\n",
+ "In a similar way, we can obtain analytical expressions for say the\n",
+ "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n",
+ "when we employ Ridge regression, allowing us again to define a confidence interval. \n",
+ "\n",
+ "It is rather straightforward to show that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see clearly that \n",
+ "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n",
+ "\n",
+ "We can also compute the variance as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n",
+ "\n",
+ "With this, we can compute the difference"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The difference is non-negative definite since each component of the\n",
+ "matrix product is non-negative definite. \n",
+ "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "\n",
+ "With all these analytical equations for both the OLS and Ridge\n",
+ "regression, we will now outline how to assess a given model. This will\n",
+ "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
+ "below) and so-called resampling methods.\n",
+ "\n",
+ "One of the quantities we have discussed as a way to measure errors is\n",
+ "the mean-squared error (MSE), mainly used for fitting of continuous\n",
+ "functions. Another choice is the absolute error.\n",
+ "\n",
+ "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
+ "we discuss the\n",
+ "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
+ "\n",
+ "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
+ "\n",
+ "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
+ "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
+ "training error reaches a saturation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Two famous\n",
+ "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
+ "\n",
+ "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
+ "popular prior to the independent bootstrap. And as the popularity of\n",
+ "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
+ "\n",
+ "The Jackknife and independent bootstrap work for\n",
+ "independent, identically distributed random variables.\n",
+ "If these conditions are not\n",
+ "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
+ "independent, identically distributed, and we only want to estimate the\n",
+ "variance of $\\overline{X}$ (which often is the case), then there is no\n",
+ "need for bootstrapping. \n",
+ "\n",
+ "\n",
+ "The Jackknife works by making many replicas of the estimator $\\widehat{\\beta}$. \n",
+ "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
+ "Let $\\boldsymbol{x}_i$ denote the vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
+ "number $i$ is left out. Using this notation, define\n",
+ "$\\widehat{\\beta}_i$ to be the estimator\n",
+ "$\\widehat{\\beta}$ computed using $\\vec{X}_i$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
+ "\n",
+ "def jackknife(data, stat):\n",
+ " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
+ " ## 'jackknifing' by leaving out an observation for each i \n",
+ " for i in range(n):\n",
+ " t[i] = stat(delete(data,i) )\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
+ "\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "# Returns mean of data samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# jackknife returns the data sample \n",
+ "t = jackknife(x, stat)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Bootstrap\n",
+ "\n",
+ "Bootstrapping is a nonparametric approach to statistical inference\n",
+ "that substitutes computation for more traditional distributional\n",
+ "assumptions and asymptotic results. Bootstrapping offers a number of\n",
+ "advantages: \n",
+ "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
+ "\n",
+ "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
+ "\n",
+ "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
+ "\n",
+ "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
+ "\n",
+ "Since $\\widehat{\\beta} = \\widehat{\\beta}(\\boldsymbol{X})$ is a function of random variables,\n",
+ "$\\widehat{\\beta}$ itself must be a random variable. Thus it has\n",
+ "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
+ "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
+ "$\\widehat{\\beta}$. You can think of this as using a histogram\n",
+ "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
+ "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
+ "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
+ "estimators. \n",
+ "\n",
+ "\n",
+ "\n",
+ "In the case that $\\widehat{\\beta}$ has\n",
+ "more than one component, and the components are independent, we use the\n",
+ "same estimator on each component separately. If the probability\n",
+ "density function of $X_i$, $p(x)$, had been known, then it would have\n",
+ "been straight forward to do this by: \n",
+ "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
+ "\n",
+ "2. Then using these numbers, we could compute a replica of $\\widehat{\\beta}$ called $\\widehat{\\beta}^*$. \n",
+ "\n",
+ "By repeated use of (1) and (2), many\n",
+ "estimates of $\\widehat{\\beta}$ could have been obtained. The\n",
+ "idea is to use the relative frequency of $\\widehat{\\beta}^*$\n",
+ "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
+ "\n",
+ "\n",
+ "But\n",
+ "unless there is enough information available about the process that\n",
+ "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
+ "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
+ "question: What if we replace $p(x)$ by the relative frequency\n",
+ "of the observation $X_i$; if we draw observations in accordance with\n",
+ "the relative frequency of the observations, will we obtain the same\n",
+ "result in some asymptotic sense? The answer is yes.\n",
+ "\n",
+ "\n",
+ "Instead of generating the histogram for the relative\n",
+ "frequency of the observation $X_i$, just draw the values\n",
+ "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
+ "$\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "The independent bootstrap works like this: \n",
+ "\n",
+ "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
+ "\n",
+ "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
+ "\n",
+ "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\beta}^*$ by evaluating $\\widehat \\beta$ under the observations $\\boldsymbol{x}^*$. \n",
+ "\n",
+ "4. Repeat this process $k$ times. \n",
+ "\n",
+ "When you are done, you can draw a histogram of the relative frequency\n",
+ "of $\\widehat \\beta^*$. This is your estimate of the probability\n",
+ "distribution $p(t)$. Using this probability distribution you can\n",
+ "estimate any statistics thereof. In principle you never draw the\n",
+ "histogram of the relative frequency of $\\widehat{\\beta}^*$. Instead\n",
+ "you use the estimators corresponding to the statistic of interest. For\n",
+ "example, if you are interested in estimating the variance of $\\widehat\n",
+ "\\beta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
+ "$\\widehat \\beta^*$.\n",
+ "\n",
+ "Before we proceed however, we need to remind ourselves about a central\n",
+ "theorem in statistics, namely the so-called **central limit theorem**.\n",
+ "This theorem plays a central role in understanding why the Bootstrap\n",
+ "(and other resampling methods) work so well on independent and\n",
+ "identically distributed variables.\n",
+ "\n",
+ "\n",
+ "Suppose we have a PDF $p(x)$ from which we generate a series $N$\n",
+ "of averages $\\langle x_i \\rangle$. Each mean value $\\langle x_i \\rangle$\n",
+ "is viewed as the average of a specific measurement, e.g., throwing \n",
+ "dice 100 times and then taking the average value, or producing a certain\n",
+ "amount of random numbers. \n",
+ "For notational ease, we set $\\langle x_i \\rangle=x_i$ in the discussion\n",
+ "which follows. \n",
+ "\n",
+ "If we compute the mean $z$ of $m$ such mean values $x_i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "z=\\frac{x_1+x_2+\\dots+x_m}{m},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "the question we pose is which is the PDF of the new variable $z$.\n",
+ "\n",
+ "\n",
+ "The probability of obtaining an average value $z$ is the product of the \n",
+ "probabilities of obtaining arbitrary individual mean values $x_i$,\n",
+ "but with the constraint that the average is $z$. We can express this through\n",
+ "the following expression"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{p}(z)=\\int dx_1p(x_1)\\int dx_2p(x_2)\\dots\\int dx_mp(x_m)\n",
+ " \\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m}),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the $\\delta$-function enbodies the constraint that the mean is $z$.\n",
+ "All measurements that lead to each individual $x_i$ are expected to\n",
+ "be independent, which in turn means that we can express $\\tilde{p}$ as the \n",
+ "product of individual $p(x_i)$. The independence assumption is important in the derivation of the central limit theorem.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we use the integral expression for the $\\delta$-function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m})=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n",
+ " dq\\exp{\\left(iq(z-\\frac{x_1+x_2+\\dots+x_m}{m})\\right)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and inserting $e^{i\\mu q-i\\mu q}$ where $\\mu$ is the mean value\n",
+ "we arrive at"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{p}(z)=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n",
+ " dq\\exp{\\left(iq(z-\\mu)\\right)}\\left[\\int_{-\\infty}^{\\infty}\n",
+ " dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the integral over $x$ resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}=\n",
+ " \\int_{-\\infty}^{\\infty}dxp(x)\n",
+ " \\left[1+\\frac{iq(\\mu-x)}{m}-\\frac{q^2(\\mu-x)^2}{2m^2}+\\dots\\right].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The second term on the rhs disappears since this is just the mean and \n",
+ "employing the definition of $\\sigma^2$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\int_{-\\infty}^{\\infty}dxp(x)e^{\\left(iq(\\mu-x)/m\\right)}=\n",
+ " 1-\\frac{q^2\\sigma^2}{2m^2}+\\dots,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left[\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m\\approx\n",
+ " \\left[1-\\frac{q^2\\sigma^2}{2m^2}+\\dots \\right]^m,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and in the limit $m\\rightarrow \\infty$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{p}(z)=\\frac{1}{\\sqrt{2\\pi}(\\sigma/\\sqrt{m})}\n",
+ " \\exp{\\left(-\\frac{(z-\\mu)^2}{2(\\sigma/\\sqrt{m})^2}\\right)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is the normal distribution with variance\n",
+ "$\\sigma^2_m=\\sigma^2/m$, where $\\sigma$ is the variance of the PDF $p(x)$\n",
+ "and $\\mu$ is also the mean of the PDF $p(x)$. \n",
+ "\n",
+ "\n",
+ "Thus, the central limit theorem states that the PDF $\\tilde{p}(z)$ of\n",
+ "the average of $m$ random values corresponding to a PDF $p(x)$ \n",
+ "is a normal distribution whose mean is the \n",
+ "mean value of the PDF $p(x)$ and whose variance is the variance\n",
+ "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n",
+ "\n",
+ "The central limit theorem leads to the well-known expression for the\n",
+ "standard deviation, given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_m=\n",
+ "\\frac{\\sigma}{\\sqrt{m}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The latter is true only if the average value is known exactly. This is obtained in the limit\n",
+ "$m\\rightarrow \\infty$ only. Because the mean and the variance are measured quantities we obtain \n",
+ "the familiar expression in statistics"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_m\\approx \n",
+ "\\frac{\\sigma}{\\sqrt{m-1}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In many cases however the above estimate for the standard deviation,\n",
+ "in particular if correlations are strong, may be too simplistic. Keep\n",
+ "in mind that we have assumed that the variables $x$ are independent\n",
+ "and identically distributed. This is obviously not always the\n",
+ "case. For example, the random numbers (or better pseudorandom numbers)\n",
+ "we generate in various calculations do always exhibit some\n",
+ "correlations.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The theorem is satisfied by a large class of PDFs. Note however that for a\n",
+ "finite $m$, it is not always possible to find a closed form /analytic expression for\n",
+ "$\\tilde{p}(x)$.\n",
+ "\n",
+ "\n",
+ "The following code starts with a Gaussian distribution with mean value\n",
+ "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
+ "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
+ "set after a given number of bootstrap operations (as many as we have\n",
+ "data points). This data set consists of estimated mean values for each\n",
+ "bootstrap operation. The histogram generated by the bootstrap method\n",
+ "shows that the distribution for these mean values is also a Gaussian,\n",
+ "centered around the mean value $\\mu=100$ but with standard deviation\n",
+ "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
+ "this case the same as the number of original data points). The value\n",
+ "of the standard deviation is what we expect from the central limit\n",
+ "theorem."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "from time import time\n",
+ "from scipy.stats import norm\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Returns mean of bootstrap samples \n",
+ "# Bootstrap algorithm\n",
+ "def bootstrap(data, datapoints):\n",
+ " t = np.zeros(datapoints)\n",
+ " n = len(data)\n",
+ " # non-parametric bootstrap \n",
+ " for i in range(datapoints):\n",
+ " t[i] = np.mean(data[np.random.randint(0,n,n)])\n",
+ " # analysis \n",
+ " print(\"Bootstrap Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %8g %14g %15g\" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))\n",
+ " return t\n",
+ "\n",
+ "# We set the mean value to 100 and the standard deviation to 15\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "# We generate random numbers according to the normal distribution\n",
+ "x = mu + sigma*np.random.randn(datapoints)\n",
+ "# bootstrap returns the data sample \n",
+ "t = bootstrap(x, datapoints)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that our new variance and from that the standard deviation, agrees with the central limit theorem.\n",
+ "\n",
+ "We plot then the histogram together with a best fit for the data set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# the histogram of the bootstrapped data (normalized data if density = True)\n",
+ "n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)\n",
+ "# add a 'best fit' line \n",
+ "y = norm.pdf(binsboot, np.mean(t), np.std(t))\n",
+ "lt = plt.plot(binsboot, y, 'b', linewidth=1)\n",
+ "plt.xlabel('x')\n",
+ "plt.ylabel('Probability')\n",
+ "plt.grid(True)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The bias-variance tradeoff\n",
+ "\n",
+ "\n",
+ "We will discuss the bias-variance tradeoff in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
+ "\n",
+ "Let us assume that the true data is generated from a noisy model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
+ "\n",
+ "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The three terms represent the square of the bias of the learning\n",
+ "method, which can be thought of as the error caused by the simplifying\n",
+ "assumptions built into the method. The second term represents the\n",
+ "variance of the chosen model and finally the last terms is variance of\n",
+ "the error $\\boldsymbol{\\epsilon}$.\n",
+ "\n",
+ "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
+ "We use a more compact notation in terms of the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which, using the abovementioned expectation values can be rewritten as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 500\n",
+ "n_boostraps = 100\n",
+ "degree = 18 # A quite high value, just to show.\n",
+ "noise = 0.1\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-1, 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",
+ "\n",
+ "# Hold out some test data that is never used in training.\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "# Combine x transformation and model into one operation.\n",
+ "# Not neccesary, but convenient.\n",
+ "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ "\n",
+ "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
+ "# for each bootstrap iteration.\n",
+ "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ "for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ "\n",
+ " # Evaluate the new model on the same test data each time.\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ "# Note: Expectations and variances taken w.r.t. different training\n",
+ "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
+ "# set in order to obtain a total value, but before this we have error/bias/variance\n",
+ "# calculated per data point in the test set.\n",
+ "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
+ "# maintains the column vector form. Dropping this yields very unexpected results.\n",
+ "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ "print('Error:', error)\n",
+ "print('Bias^2:', bias)\n",
+ "print('Var:', variance)\n",
+ "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
+ "\n",
+ "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
+ "plt.scatter(x_test, y_test, label='Data points')\n",
+ "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 40\n",
+ "n_boostraps = 100\n",
+ "maxdegree = 14\n",
+ "\n",
+ "\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",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = 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",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The bias-variance tradeoff summarizes the fundamental tension in\n",
+ "machine learning, particularly supervised learning, between the\n",
+ "complexity of a model and the amount of training data needed to train\n",
+ "it. Since data is often limited, in practice it is often useful to\n",
+ "use a less-complex model with higher bias, that is a model whose asymptotic\n",
+ "performance is worse than another model because it is easier to\n",
+ "train and less sensitive to sampling noise arising from having a\n",
+ "finite-sized training dataset (smaller variance). \n",
+ "\n",
+ "\n",
+ "\n",
+ "The above equations tell us that in\n",
+ "order to minimize the expected test error, we need to select a\n",
+ "statistical learning method that simultaneously achieves low variance\n",
+ "and low bias. Note that variance is inherently a nonnegative quantity,\n",
+ "and squared bias is also nonnegative. Hence, we see that the expected\n",
+ "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
+ "\n",
+ "\n",
+ "What do we mean by the variance and bias of a statistical learning\n",
+ "method? The variance refers to the amount by which our model would change if we\n",
+ "estimated it using a different training data set. Since the training\n",
+ "data are used to fit the statistical learning method, different\n",
+ "training data sets will result in a different estimate. But ideally the\n",
+ "estimate for our model should not vary too much between training\n",
+ "sets. However, if a method has high variance then small changes in\n",
+ "the training data can result in large changes in the model. In general, more\n",
+ "flexible statistical methods have higher variance.\n",
+ "\n",
+ "\n",
+ "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "============================\n",
+ "Underfitting vs. Overfitting\n",
+ "============================\n",
+ "\n",
+ "This example demonstrates the problems of underfitting and overfitting and\n",
+ "how we can use linear regression with polynomial features to approximate\n",
+ "nonlinear functions. The plot shows the function that we want to approximate,\n",
+ "which is a part of the cosine function. In addition, the samples from the\n",
+ "real function and the approximations of different models are displayed. The\n",
+ "models have polynomial features of different degrees. We can see that a\n",
+ "linear function (polynomial with degree 1) is not sufficient to fit the\n",
+ "training samples. This is called **underfitting**. A polynomial of degree 4\n",
+ "approximates the true function almost perfectly. However, for higher degrees\n",
+ "the model will **overfit** the training data, i.e. it learns the noise of the\n",
+ "training data.\n",
+ "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
+ "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
+ "set, the higher, the less likely the model generalizes correctly from the\n",
+ "training data.\n",
+ "\"\"\"\n",
+ "\n",
+ "print(__doc__)\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "def true_fun(X):\n",
+ " return np.cos(1.5 * np.pi * X)\n",
+ "\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "n_samples = 30\n",
+ "degrees = [1, 4, 15]\n",
+ "\n",
+ "X = np.sort(np.random.rand(n_samples))\n",
+ "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
+ "\n",
+ "plt.figure(figsize=(14, 5))\n",
+ "for i in range(len(degrees)):\n",
+ " ax = plt.subplot(1, len(degrees), i + 1)\n",
+ " plt.setp(ax, xticks=(), yticks=())\n",
+ "\n",
+ " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
+ " include_bias=False)\n",
+ " linear_regression = LinearRegression()\n",
+ " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
+ " (\"linear_regression\", linear_regression)])\n",
+ " pipeline.fit(X[:, np.newaxis], y)\n",
+ "\n",
+ " # Evaluate the models using crossvalidation\n",
+ " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
+ " scoring=\"neg_mean_squared_error\", cv=10)\n",
+ "\n",
+ " X_test = np.linspace(0, 1, 100)\n",
+ " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
+ " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
+ " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
+ " plt.xlabel(\"x\")\n",
+ " plt.ylabel(\"y\")\n",
+ " plt.xlim((0, 1))\n",
+ " plt.ylim((-2, 2))\n",
+ " plt.legend(loc=\"best\")\n",
+ " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
+ " degrees[i], -scores.mean(), scores.std()))\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "testerror = np.zeros(Maxpolydegree)\n",
+ "trainingerror = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "\n",
+ "trials = 100\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ "\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " testerror[polydegree] = 0.0\n",
+ " trainingerror[polydegree] = 0.0\n",
+ " for samples in range(trials):\n",
+ " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ " model = LinearRegression(fit_intercept=False).fit(x_train, y_train)\n",
+ " ypred = model.predict(x_train)\n",
+ " ytilde = model.predict(x_test)\n",
+ " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
+ " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
+ "\n",
+ " testerror[polydegree] /= trials\n",
+ " trainingerror[polydegree] /= trials\n",
+ " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
+ " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
+ " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
+ "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Cross-validation\n",
+ "\n",
+ "When the repetitive splitting of the data set is done randomly,\n",
+ "samples may accidently end up in a fast majority of the splits in\n",
+ "either training or test set. Such samples may have an unbalanced\n",
+ "influence on either model building or prediction evaluation. To avoid\n",
+ "this $k$-fold cross-validation structures the data splitting. The\n",
+ "samples are divided into $k$ more or less equally sized exhaustive and\n",
+ "mutually exclusive subsets. In turn (at each split) one of these\n",
+ "subsets plays the role of the test set while the union of the\n",
+ "remaining subsets constitutes the training set. Such a splitting\n",
+ "warrants a balanced representation of each sample in both training and\n",
+ "test set over the splits. Still the division into the $k$ subsets\n",
+ "involves a degree of randomness. This may be fully excluded when\n",
+ "choosing $k=n$. This particular case is referred to as leave-one-out\n",
+ "cross-validation (LOOCV). \n",
+ "\n",
+ "\n",
+ "* Define a range of interest for the penalty parameter.\n",
+ "\n",
+ "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
+ "\n",
+ "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
+ "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
+ "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "\n",
+ "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
+ "\n",
+ "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the various values of $k$\n",
+ "\n",
+ "1. shuffle the dataset randomly.\n",
+ "\n",
+ "2. Split the dataset into $k$ groups.\n",
+ "\n",
+ "3. For each unique group:\n",
+ "\n",
+ "a. Decide which group to use as set for test data\n",
+ "\n",
+ "b. Take the remaining groups as a training data set\n",
+ "\n",
+ "c. Fit a model on the training set and evaluate it on the test set\n",
+ "\n",
+ "d. Retain the evaluation score and discard the model\n",
+ "\n",
+ "\n",
+ "5. Summarize the model using the sample of model evaluation scores\n",
+ "\n",
+ "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\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",
+ "# Generate the data.\n",
+ "nsamples = 100\n",
+ "x = np.random.randn(nsamples)\n",
+ "y = 3*x**2 + np.random.randn(nsamples)\n",
+ "\n",
+ "## Cross-validation on Ridge regression using KFold only\n",
+ "\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 6)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "# Perform the cross-validation to estimate MSE\n",
+ "scores_KFold = np.zeros((nlambdas, k))\n",
+ "\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " j = 0\n",
+ " for train_inds, test_inds in kfold.split(x):\n",
+ " xtrain = x[train_inds]\n",
+ " ytrain = y[train_inds]\n",
+ "\n",
+ " xtest = x[test_inds]\n",
+ " ytest = y[test_inds]\n",
+ "\n",
+ " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
+ " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
+ "\n",
+ " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
+ " ypred = ridge.predict(Xtest)\n",
+ "\n",
+ " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
+ "\n",
+ " j += 1\n",
+ " i += 1\n",
+ "\n",
+ "\n",
+ "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
+ "\n",
+ "## Cross-validation using cross_val_score from sklearn along with KFold\n",
+ "\n",
+ "# kfold is an instance initialized above as:\n",
+ "# kfold = KFold(n_splits = k)\n",
+ "\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ "\n",
+ " X = poly.fit_transform(x[:, np.newaxis])\n",
+ " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
+ "\n",
+ " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
+ " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ " i += 1\n",
+ "\n",
+ "## Plot and compare the slightly different ways to perform cross-validation\n",
+ "\n",
+ "plt.figure()\n",
+ "\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('mse')\n",
+ "\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "More examples of the application of cross-validation follow here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "k =5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ " OLS = LinearRegression(fit_intercept=False)\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
+ "#[:, np.newaxis]\n",
+ " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that we have kept the intercept in the first column of design matrix $\\boldsymbol{X}$. When we call the corresponding **Scikit-Learn** function we need thus to set the intercept to **False**. Libraries like **Scikit-Learn** normally scale the design matrix and does not fit intercept. See the discussions below.\n",
+ "\n",
+ "## More on Rescaling data\n",
+ "\n",
+ "We end this chapter by adding some words on scaling and how to deal with the intercept for regression cases.\n",
+ "\n",
+ "When you are comparing your own code with for example **Scikit-Learn**'s\n",
+ "library, there are some technicalities to keep in mind. The examples\n",
+ "here demonstrate some of these aspects with potential pitfalls.\n",
+ "\n",
+ "The discussion here focuses on the role of the intercept, how we can\n",
+ "set up the design matrix, what scaling we should use and other topics\n",
+ "which tend confuse us.\n",
+ "\n",
+ "The intercept can be interpreted as the expected value of our\n",
+ "target/output variables when all other predictors are set to zero.\n",
+ "Thus, if we cannot assume that the expected outputs/targets are zero\n",
+ "when all predictors are zero (the columns in the design matrix), it\n",
+ "may be a bad idea to implement a model which penalizes the intercept.\n",
+ "Furthermore, in for example Ridge and Lasso regression, the default solutions\n",
+ "from the library **Scikit-Learn** (when not shrinking $\\beta_0$) for the unknown parameters\n",
+ "$\\boldsymbol{\\beta}$, are derived under the assumption that both $\\boldsymbol{y}$ and\n",
+ "$\\boldsymbol{X}$ are zero centered, that is we subtract the mean values.\n",
+ "\n",
+ "\n",
+ "If our predictors represent different scales, then it is important to\n",
+ "standardize the design matrix $\\boldsymbol{X}$ by subtracting the mean of each\n",
+ "column from the corresponding column and dividing the column with its\n",
+ "standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,\n",
+ "the results may differ. \n",
+ "\n",
+ "The\n",
+ "[Standardscaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n",
+ "function in **Scikit-Learn** does this for us. For the data sets we\n",
+ "have been studying in our various examples, the data are in many cases\n",
+ "already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a\n",
+ "survey of your data, with a critical assessment of them in case you need to scale the data.\n",
+ "\n",
+ "If you need to scale the data, not doing so will give an *unfair*\n",
+ "penalization of the parameters since their magnitude depends on the\n",
+ "scale of their corresponding predictor.\n",
+ "\n",
+ "Suppose as an example that you \n",
+ "you have an input variable given by the heights of different persons.\n",
+ "Human height might be measured in inches or meters or\n",
+ "kilometers. If measured in kilometers, a standard linear regression\n",
+ "model with this predictor would probably give a much bigger\n",
+ "coefficient term, than if measured in millimeters.\n",
+ "This can clearly lead to problems in evaluating the cost/loss functions.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Keep in mind that when you transform your data set before training a model, the same transformation needs to be done\n",
+ "on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "#Model training, we compute the mean value of y and X\n",
+ "y_train_mean = np.mean(y_train)\n",
+ "X_train_mean = np.mean(X_train,axis=0)\n",
+ "X_train = X_train - X_train_mean\n",
+ "y_train = y_train - y_train_mean\n",
+ "\n",
+ "# The we fit our model with the training data\n",
+ "trained_model = some_model.fit(X_train,y_train)\n",
+ "\n",
+ "\n",
+ "#Model prediction, we need also to transform our data set used for the prediction.\n",
+ "X_test = X_test - X_train_mean #Use mean from training data\n",
+ "y_pred = trained_model(X_test)\n",
+ "y_pred = y_pred + y_train_mean\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us try to understand what this may imply mathematically when we\n",
+ "subtract the mean values, also known as *zero centering*. For\n",
+ "simplicity, we will focus on ordinary regression, as done in the above example.\n",
+ "\n",
+ "The cost/loss function for regression is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Recall also that we use the squared value. This expression can lead to an\n",
+ "increased penalty for higher differences between predicted and\n",
+ "output/target values.\n",
+ "\n",
+ "What we have done is to single out the $\\beta_0$ term in the\n",
+ "definition of the mean squared error (MSE). The design matrix $X$\n",
+ "does in this case not contain any intercept column. When we take the\n",
+ "derivative with respect to $\\beta_0$, we want the derivative to obey"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for all $j$. For $\\beta_0$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying away the constant $2/n$, we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us specialize first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n",
+ "Our result for $\\beta_0$ simplifies then to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We obtain then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we define"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu_{\\boldsymbol{x}_1}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the mean value of the outputs as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0 = \\mu_y - \\beta_1\\mu_{\\boldsymbol{x}_1}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the general case with more parameters than $\\beta_0$ and $\\beta_1$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite the latter equation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\sum_{j=1}^{p-1} \\mu_{\\boldsymbol{x}_j}\\beta_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu_{\\boldsymbol{x}_j}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{ij},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "the mean value for all elements of the column vector $\\boldsymbol{x}_j$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n",
+ "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n",
+ "\n",
+ "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What does this mean? And why do we insist on all this? Let us look at some examples.\n",
+ "\n",
+ "\n",
+ "This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only.\n",
+ "Note also that we do not split the data into training and test."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "\n",
+ "np.random.seed(2021)\n",
+ "\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",
+ "def fit_beta(X, y):\n",
+ " return np.linalg.pinv(X.T @ X) @ X.T @ y\n",
+ "\n",
+ "\n",
+ "true_beta = [2, 0.5, 3.7]\n",
+ "\n",
+ "x = np.linspace(0, 1, 11)\n",
+ "y = np.sum(\n",
+ " np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0\n",
+ ") + 0.1 * np.random.normal(size=len(x))\n",
+ "\n",
+ "degree = 3\n",
+ "X = np.zeros((len(x), degree))\n",
+ "\n",
+ "# Include the intercept in the design matrix\n",
+ "for p in range(degree):\n",
+ " X[:, p] = x ** p\n",
+ "\n",
+ "beta = fit_beta(X, y)\n",
+ "\n",
+ "# Intercept is included in the design matrix\n",
+ "skl = LinearRegression(fit_intercept=False).fit(X, y)\n",
+ "\n",
+ "print(f\"True beta: {true_beta}\")\n",
+ "print(f\"Fitted beta: {beta}\")\n",
+ "print(f\"Sklearn fitted beta: {skl.coef_}\")\n",
+ "ypredictOwn = X @ beta\n",
+ "ypredictSKL = skl.predict(X)\n",
+ "print(f\"MSE with intercept column\")\n",
+ "print(MSE(y,ypredictOwn))\n",
+ "print(f\"MSE with intercept column from SKL\")\n",
+ "print(MSE(y,ypredictSKL))\n",
+ "\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x, y, label=\"Data\")\n",
+ "plt.plot(x, X @ beta, label=\"Fit\")\n",
+ "plt.plot(x, skl.predict(X), label=\"Sklearn (fit_intercept=False)\")\n",
+ "\n",
+ "\n",
+ "# Do not include the intercept in the design matrix\n",
+ "X = np.zeros((len(x), degree - 1))\n",
+ "\n",
+ "for p in range(degree - 1):\n",
+ " X[:, p] = x ** (p + 1)\n",
+ "\n",
+ "# Intercept is not included in the design matrix\n",
+ "skl = LinearRegression(fit_intercept=True).fit(X, y)\n",
+ "\n",
+ "# Use centered values for X and y when computing coefficients\n",
+ "y_offset = np.average(y, axis=0)\n",
+ "X_offset = np.average(X, axis=0)\n",
+ "\n",
+ "beta = fit_beta(X - X_offset, y - y_offset)\n",
+ "intercept = np.mean(y_offset - X_offset @ beta)\n",
+ "\n",
+ "print(f\"Manual intercept: {intercept}\")\n",
+ "print(f\"Fitted beta (wiothout intercept): {beta}\")\n",
+ "print(f\"Sklearn intercept: {skl.intercept_}\")\n",
+ "print(f\"Sklearn fitted beta (without intercept): {skl.coef_}\")\n",
+ "ypredictOwn = X @ beta\n",
+ "ypredictSKL = skl.predict(X)\n",
+ "print(f\"MSE with Manual intercept\")\n",
+ "print(MSE(y,ypredictOwn+intercept))\n",
+ "print(f\"MSE with Sklearn intercept\")\n",
+ "print(MSE(y,ypredictSKL))\n",
+ "\n",
+ "plt.plot(x, X @ beta + intercept, \"--\", label=\"Fit (manual intercept)\")\n",
+ "plt.plot(x, skl.predict(X), \"--\", label=\"Sklearn (fit_intercept=True)\")\n",
+ "plt.grid()\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The intercept is the value of our output/target variable\n",
+ "when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). \n",
+ "\n",
+ "Printing the MSE, we see first that both methods give the same MSE, as\n",
+ "they should. However, when we move to for example Ridge regression,\n",
+ "the way we treat the intercept may give a larger or smaller MSE,\n",
+ "meaning that the MSE can be penalized by the value of the\n",
+ "intercept. Not including the intercept in the fit, means that the\n",
+ "regularization term does not include $\\beta_0$. For different values\n",
+ "of $\\lambda$, this may lead to differeing MSE values. \n",
+ "\n",
+ "To remind the reader, the regularization term, with the intercept in Ridge regression, is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=0}^{p-1}\\beta_j^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "but when we take out the intercept, this equation becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=1}^{p-1}\\beta_j^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Lasso regression we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_1 = \\lambda \\sum_{j=1}^{p-1}\\vert\\beta_j\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It means that, when scaling the design matrix and the outputs/targets,\n",
+ "by subtracting the mean values, we have an optimization problem which\n",
+ "is not penalized by the intercept. The MSE value can then be smaller\n",
+ "since it focuses only on the remaining quantities. If we however bring\n",
+ "back the intercept, we will get a MSE which then contains the\n",
+ "intercept.\n",
+ "\n",
+ "\n",
+ "Armed with this wisdom, we attempt first to simply set the intercept equal to **False** in our implementation of Ridge regression for our well-known vanilla data set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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 import linear_model\n",
+ "\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",
+ "n = 100\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n",
+ "\n",
+ "Maxpolydegree = 20\n",
+ "X = np.zeros((n,Maxpolydegree))\n",
+ "#We include explicitely the intercept column\n",
+ "for degree in range(Maxpolydegree):\n",
+ " X[:,degree] = x**degree\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",
+ "\n",
+ "p = Maxpolydegree\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 6\n",
+ "MSEOwnRidgePredict = np.zeros(nlambdas)\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 2, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # Note: we include the intercept column and no scaling\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeOwnRidge = X_train @ OwnRidgeBeta\n",
+ " ypredictOwnRidge = X_test @ OwnRidgeBeta\n",
+ " ytildeRidge = RegRidge.predict(X_train)\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " print(\"Beta values for own Ridge implementation\")\n",
+ " print(OwnRidgeBeta)\n",
+ " print(\"Beta values for Scikit-Learn Ridge implementation\")\n",
+ " print(RegRidge.coef_)\n",
+ " print(\"MSE values for own Ridge implementation\")\n",
+ " print(MSEOwnRidgePredict[i])\n",
+ " print(\"MSE values for Scikit-Learn Ridge implementation\")\n",
+ " print(MSERidgePredict[i])\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The results here agree when we force **Scikit-Learn**'s Ridge function to include the first column in our design matrix.\n",
+ "We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.\n",
+ "What happens if we do not include the intercept in our fit?\n",
+ "Let us see how we can change this code by zero centering."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "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 import linear_model\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/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(315)\n",
+ "\n",
+ "n = 100\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n",
+ "\n",
+ "Maxpolydegree = 20\n",
+ "X = np.zeros((n,Maxpolydegree-1))\n",
+ "\n",
+ "for degree in range(1,Maxpolydegree): #No intercept column\n",
+ " X[:,degree-1] = x**(degree)\n",
+ "\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",
+ "\n",
+ "#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable\n",
+ "X_train_mean = np.mean(X_train,axis=0)\n",
+ "#Center by removing mean from each feature\n",
+ "X_train_scaled = X_train - X_train_mean \n",
+ "X_test_scaled = X_test - X_train_mean\n",
+ "#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)\n",
+ "#Remove the intercept from the training data.\n",
+ "y_scaler = np.mean(y_train) \n",
+ "y_train_scaled = y_train - y_scaler \n",
+ "\n",
+ "p = Maxpolydegree-1\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 6\n",
+ "MSEOwnRidgePredict = np.zeros(nlambdas)\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "\n",
+ "lambdas = np.logspace(-4, 2, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)\n",
+ " intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data\n",
+ " #Add intercept to prediction\n",
+ " ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler \n",
+ " RegRidge = linear_model.Ridge(lmb)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " print(\"Beta values for own Ridge implementation\")\n",
+ " print(OwnRidgeBeta) #Intercept is given by mean of target variable\n",
+ " print(\"Beta values for Scikit-Learn Ridge implementation\")\n",
+ " print(RegRidge.coef_)\n",
+ " print('Intercept from own implementation:')\n",
+ " print(intercept_)\n",
+ " print('Intercept from Scikit-Learn Ridge implementation')\n",
+ " print(RegRidge.intercept_)\n",
+ " print(\"MSE values for own Ridge implementation\")\n",
+ " print(MSEOwnRidgePredict[i])\n",
+ " print(\"MSE values for Scikit-Learn Ridge implementation\")\n",
+ " print(MSERidgePredict[i])\n",
+ "\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see here, when compared to the code which includes explicitely the\n",
+ "intercept column, that our MSE value is actually smaller. This is\n",
+ "because the regularization term does not include the intercept value\n",
+ "$\\beta_0$ in the fitting. This applies to Lasso regularization as\n",
+ "well. It means that our optimization is now done only with the\n",
+ "centered matrix and/or vector that enter the fitting procedure. Note\n",
+ "also that the problem with the intercept occurs mainly in these type\n",
+ "of polynomial fitting problem.\n",
+ "\n",
+ "The next example is indeed an example where all these discussions about the role of intercept are not present.\n",
+ "\n",
+ "## More complicated Example: The Ising model\n",
+ "\n",
+ "The one-dimensional Ising model with nearest neighbor interaction, no\n",
+ "external field and a constant coupling constant $J$ is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " H = -J \\sum_{k}^L s_k s_{k + 1},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins\n",
+ "in the system is determined by $L$. For the one-dimensional system\n",
+ "there is no phase transition.\n",
+ "\n",
+ "We will look at a system of $L = 40$ spins with a coupling constant of\n",
+ "$J = 1$. To get enough training data we will generate 10000 states\n",
+ "with their respective energies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
+ "import seaborn as sns\n",
+ "import scipy.linalg as scl\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "import tqdm\n",
+ "sns.set(color_codes=True)\n",
+ "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n",
+ "\n",
+ "L = 40\n",
+ "n = int(1e4)\n",
+ "\n",
+ "spins = np.random.choice([-1, 1], size=(n, L))\n",
+ "J = 1.0\n",
+ "\n",
+ "energies = np.zeros(n)\n",
+ "\n",
+ "for i in range(n):\n",
+ " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we use ordinary least squares\n",
+ "regression to predict the energy for the nearest neighbor\n",
+ "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n",
+ "around. We will use linear regression to fit a value for\n",
+ "the coupling constant to achieve this.\n",
+ "\n",
+ "A more general form for the one-dimensional Ising model is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n",
+ "\\label{_auto2} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we allow for interactions beyond the nearest neighbors and a state dependent\n",
+ "coupling constant. This latter expression can be formulated as\n",
+ "a matrix-product"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\boldsymbol{H} = \\boldsymbol{X} J,\n",
+ "\\label{_auto3} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the\n",
+ "elements $-J_{jk}$. This form of writing the energy fits perfectly\n",
+ "with the form utilized in linear regression, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n",
+ "\\label{_auto4} \\tag{4}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We split the data in training and test data as discussed in the previous example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "X = np.zeros((n, L ** 2))\n",
+ "for i in range(n):\n",
+ " X[i] = np.outer(spins[i], spins[i]).ravel()\n",
+ "y = energies\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the ordinary least squares method we choose the cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " C(\\boldsymbol{X}, \\boldsymbol{\\beta})= \\frac{1}{n}\\left\\{(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})\\right\\}.\n",
+ "\\label{_auto5} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We then find the extremal point of $C$ by taking the derivative with respect to $\\boldsymbol{\\beta}$ as discussed above.\n",
+ "This yields the expression for $\\boldsymbol{\\beta}$ to be"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta} = \\frac{\\boldsymbol{X}^T \\boldsymbol{y}}{\\boldsymbol{X}^T \\boldsymbol{X}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which immediately imposes some requirements on $\\boldsymbol{X}$ as there must exist\n",
+ "an inverse of $\\boldsymbol{X}^T \\boldsymbol{X}$. If the expression we are modeling contains an\n",
+ "intercept, i.e., a constant term, we must make sure that the\n",
+ "first column of $\\boldsymbol{X}$ consists of $1$. We do this here"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "X_train_own = np.concatenate(\n",
+ " (np.ones(len(X_train))[:, np.newaxis], X_train),\n",
+ " axis=1\n",
+ ")\n",
+ "X_test_own = np.concatenate(\n",
+ " (np.ones(len(X_test))[:, np.newaxis], X_test),\n",
+ " axis=1\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Doing the inversion directly turns out to be a bad idea since the matrix\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$ is singular. An alternative approach is to use the **singular\n",
+ "value decomposition**. Using the definition of the Moore-Penrose\n",
+ "pseudoinverse we can write the equation for $\\boldsymbol{\\beta}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta} = \\boldsymbol{X}^{+}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the pseudoinverse of $\\boldsymbol{X}$ is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{+} = \\frac{\\boldsymbol{X}^T}{\\boldsymbol{X}^T\\boldsymbol{X}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using singular value decomposition we can decompose the matrix $\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma} \\boldsymbol{V}^T$,\n",
+ "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal(unitary) matrices and $\\boldsymbol{\\Sigma}$ contains the singular values (more details below).\n",
+ "where $X^{+} = V\\Sigma^{+} U^T$. This reduces the equation for\n",
+ "$\\omega$ to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\boldsymbol{\\beta} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^{+} \\boldsymbol{U}^T \\boldsymbol{y}.\n",
+ "\\label{_auto6} \\tag{6}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that solving this equation by actually doing the pseudoinverse\n",
+ "(which is what we will do) is not a good idea as this operation scales\n",
+ "as $\\mathcal{O}(n^3)$, where $n$ is the number of elements in a\n",
+ "general matrix. Instead, doing $QR$-factorization and solving the\n",
+ "linear system as an equation would reduce this down to\n",
+ "$\\mathcal{O}(n^2)$ operations."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n",
+ " u, s, v = scl.svd(x)\n",
+ " return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "beta = ols_svd(X_train_own,y_train)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "J = beta[1:].reshape(L, L)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A way of looking at the coefficients in $J$ is to plot the matrices as images."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "fig = plt.figure(figsize=(20, 14))\n",
+ "im = plt.imshow(J, **cmap_args)\n",
+ "plt.title(\"OLS\", fontsize=18)\n",
+ "plt.xticks(fontsize=18)\n",
+ "plt.yticks(fontsize=18)\n",
+ "cb = fig.colorbar(im)\n",
+ "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is interesting to note that OLS\n",
+ "considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as\n",
+ "valid matrix elements for $J$.\n",
+ "In our discussion below on hyperparameters and Ridge and Lasso regression we will see that\n",
+ "this problem can be removed, partly and only with Lasso regression. \n",
+ "\n",
+ "In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us now \n",
+ "focus on Ridge and Lasso regression as well. We repeat some of the\n",
+ "basic parts of the Ising model and the setup of the training and test\n",
+ "data. The one-dimensional Ising model with nearest neighbor\n",
+ "interaction, no external field and a constant coupling constant $J$ is\n",
+ "given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " H = -J \\sum_{k}^L s_k s_{k + 1},\n",
+ "\\label{_auto7} \\tag{7}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition.\n",
+ "\n",
+ "We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
+ "import seaborn as sns\n",
+ "import scipy.linalg as scl\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "import sklearn.linear_model as skl\n",
+ "import tqdm\n",
+ "sns.set(color_codes=True)\n",
+ "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n",
+ "\n",
+ "L = 40\n",
+ "n = int(1e4)\n",
+ "\n",
+ "spins = np.random.choice([-1, 1], size=(n, L))\n",
+ "J = 1.0\n",
+ "\n",
+ "energies = np.zeros(n)\n",
+ "\n",
+ "for i in range(n):\n",
+ " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A more general form for the one-dimensional Ising model is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n",
+ "\\label{_auto8} \\tag{8}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we allow for interactions beyond the nearest neighbors and a more\n",
+ "adaptive coupling matrix. This latter expression can be formulated as\n",
+ "a matrix-product on the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " H = X J,\n",
+ "\\label{_auto9} \\tag{9}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the\n",
+ "elements $-J_{jk}$. This form of writing the energy fits perfectly\n",
+ "with the form utilized in linear regression, viz."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon}.\n",
+ "\\label{_auto10} \\tag{10}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We organize the data as we did above"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "X = np.zeros((n, L ** 2))\n",
+ "for i in range(n):\n",
+ " X[i] = np.outer(spins[i], spins[i]).ravel()\n",
+ "y = energies\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)\n",
+ "\n",
+ "X_train_own = np.concatenate(\n",
+ " (np.ones(len(X_train))[:, np.newaxis], X_train),\n",
+ " axis=1\n",
+ ")\n",
+ "\n",
+ "X_test_own = np.concatenate(\n",
+ " (np.ones(len(X_test))[:, np.newaxis], X_test),\n",
+ " axis=1\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We will do all fitting with **Scikit-Learn**,"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "clf = skl.LinearRegression().fit(X_train, y_train)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When extracting the $J$-matrix we make sure to remove the intercept"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "J_sk = clf.coef_.reshape(L, L)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And then we plot the results"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "fig = plt.figure(figsize=(20, 14))\n",
+ "im = plt.imshow(J_sk, **cmap_args)\n",
+ "plt.title(\"LinearRegression from Scikit-learn\", fontsize=18)\n",
+ "plt.xticks(fontsize=18)\n",
+ "plt.yticks(fontsize=18)\n",
+ "cb = fig.colorbar(im)\n",
+ "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The results agree perfectly with our previous discussion where we used our own code.\n",
+ "\n",
+ "\n",
+ "Having explored the ordinary least squares we move on to ridge\n",
+ "regression. In ridge regression we include a **regularizer**. This\n",
+ "involves a new cost function which leads to a new estimate for the\n",
+ "weights $\\boldsymbol{\\beta}$. This results in a penalized regression problem. The\n",
+ "cost function is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "6\n",
+ "0\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "M\n",
+ "A\n",
+ "T\n",
+ "H\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "_lambda = 0.1\n",
+ "clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)\n",
+ "J_ridge_sk = clf_ridge.coef_.reshape(L, L)\n",
+ "fig = plt.figure(figsize=(20, 14))\n",
+ "im = plt.imshow(J_ridge_sk, **cmap_args)\n",
+ "plt.title(\"Ridge from Scikit-learn\", fontsize=18)\n",
+ "plt.xticks(fontsize=18)\n",
+ "plt.yticks(fontsize=18)\n",
+ "cb = fig.colorbar(im)\n",
+ "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the **Least Absolute Shrinkage and Selection Operator** (LASSO)-method we get a third cost function."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " C(\\boldsymbol{X}, \\boldsymbol{\\beta}; \\lambda) = (\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y}) + \\lambda \\sqrt{\\boldsymbol{\\beta}^T\\boldsymbol{\\beta}}.\n",
+ "\\label{_auto12} \\tag{12}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from **Scikit-Learn**."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)\n",
+ "J_lasso_sk = clf_lasso.coef_.reshape(L, L)\n",
+ "fig = plt.figure(figsize=(20, 14))\n",
+ "im = plt.imshow(J_lasso_sk, **cmap_args)\n",
+ "plt.title(\"Lasso from Scikit-learn\", fontsize=18)\n",
+ "plt.xticks(fontsize=18)\n",
+ "plt.yticks(fontsize=18)\n",
+ "cb = fig.colorbar(im)\n",
+ "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is quite striking how LASSO breaks the symmetry of the coupling\n",
+ "constant as opposed to ridge and OLS. We get a sparse solution with\n",
+ "$J_{j, j + 1} = -1$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We see how the different models perform for a different set of values for $\\lambda$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "lambdas = np.logspace(-4, 5, 10)\n",
+ "\n",
+ "train_errors = {\n",
+ " \"ols_sk\": np.zeros(lambdas.size),\n",
+ " \"ridge_sk\": np.zeros(lambdas.size),\n",
+ " \"lasso_sk\": np.zeros(lambdas.size)\n",
+ "}\n",
+ "\n",
+ "test_errors = {\n",
+ " \"ols_sk\": np.zeros(lambdas.size),\n",
+ " \"ridge_sk\": np.zeros(lambdas.size),\n",
+ " \"lasso_sk\": np.zeros(lambdas.size)\n",
+ "}\n",
+ "\n",
+ "plot_counter = 1\n",
+ "\n",
+ "fig = plt.figure(figsize=(32, 54))\n",
+ "\n",
+ "for i, _lambda in enumerate(tqdm.tqdm(lambdas)):\n",
+ " for key, method in zip(\n",
+ " [\"ols_sk\", \"ridge_sk\", \"lasso_sk\"],\n",
+ " [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]\n",
+ " ):\n",
+ " method = method.fit(X_train, y_train)\n",
+ "\n",
+ " train_errors[key][i] = method.score(X_train, y_train)\n",
+ " test_errors[key][i] = method.score(X_test, y_test)\n",
+ "\n",
+ " omega = method.coef_.reshape(L, L)\n",
+ "\n",
+ " plt.subplot(10, 5, plot_counter)\n",
+ " plt.imshow(omega, **cmap_args)\n",
+ " plt.title(r\"%s, $\\lambda = %.4f$\" % (key, _lambda))\n",
+ " plot_counter += 1\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that LASSO reaches a good solution for low\n",
+ "values of $\\lambda$, but will \"wither\" when we increase $\\lambda$ too\n",
+ "much. Ridge is more stable over a larger range of values for\n",
+ "$\\lambda$, but eventually also fades away.\n",
+ "\n",
+ "\n",
+ "To determine which value of $\\lambda$ is best we plot the accuracy of\n",
+ "the models when predicting the training and the testing set. We expect\n",
+ "the accuracy of the training set to be quite good, but if the accuracy\n",
+ "of the testing set is much lower this tells us that we might be\n",
+ "subject to an overfit model. The ideal scenario is an accuracy on the\n",
+ "testing set that is close to the accuracy of the training set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "fig = plt.figure(figsize=(20, 14))\n",
+ "\n",
+ "colors = {\n",
+ " \"ols_sk\": \"r\",\n",
+ " \"ridge_sk\": \"y\",\n",
+ " \"lasso_sk\": \"c\"\n",
+ "}\n",
+ "\n",
+ "for key in train_errors:\n",
+ " plt.semilogx(\n",
+ " lambdas,\n",
+ " train_errors[key],\n",
+ " colors[key],\n",
+ " label=\"Train {0}\".format(key),\n",
+ " linewidth=4.0\n",
+ " )\n",
+ "\n",
+ "for key in test_errors:\n",
+ " plt.semilogx(\n",
+ " lambdas,\n",
+ " test_errors[key],\n",
+ " colors[key] + \"--\",\n",
+ " label=\"Test {0}\".format(key),\n",
+ " linewidth=4.0\n",
+ " )\n",
+ "plt.legend(loc=\"best\", fontsize=18)\n",
+ "plt.xlabel(r\"$\\lambda$\", fontsize=18)\n",
+ "plt.ylabel(r\"$R^2$\", fontsize=18)\n",
+ "plt.tick_params(labelsize=18)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "From the above figure we can see that LASSO with $\\lambda = 10^{-2}$\n",
+ "achieves a very good accuracy on the test set. This by far surpasses the\n",
+ "other models for all values of $\\lambda$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Exercises and Projects\n",
+ "\n",
+ "\n",
+ "\n",
+ "The main aim of this project is to study in more detail various\n",
+ "regression methods, including the Ordinary Least Squares (OLS) method,\n",
+ "The total score is **100** points. Each subtask has its own final score.\n",
+ "\n",
+ "\n",
+ "We will first study how to fit polynomials to a specific\n",
+ "two-dimensional function called [Franke's\n",
+ "function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n",
+ "is a function which has been widely used when testing various\n",
+ "interpolation and fitting algorithms. Furthermore, after having\n",
+ "established the model and the method, we will employ resamling\n",
+ "techniques such as cross-validation and/or bootstrap in order to perform a\n",
+ "proper assessment of our models. We will also study in detail the\n",
+ "so-called Bias-Variance trade off.\n",
+ "\n",
+ "\n",
+ "The Franke function, which is a weighted sum of four exponentials reads as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n",
+ "&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The function will be defined for $x,y\\in [0,1]$. Our first step will\n",
+ "be to perform an OLS regression analysis of this function, trying out\n",
+ "a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n",
+ "x^2, y^2, xy, \\dots]$. We will also include bootstrap first as\n",
+ "a resampling technique. After that we will include the cross-validation technique. As in homeworks 1 and 2, we can use a uniform\n",
+ "distribution to set up the arrays of values for $x$ and $y$, or as in\n",
+ "the example below just a set of fixed \n",
+ "values for $x$ and $y$ with a given step\n",
+ "size. We will fit a\n",
+ "function (for example a polynomial) of $x$ and $y$. Thereafter we\n",
+ "will repeat much of the same procedure using the Ridge and Lasso\n",
+ "regression methods, introducing thus a dependence on the bias\n",
+ "(penalty) $\\lambda$.\n",
+ "\n",
+ "Finally we are going to use (real) digital terrain data and try to\n",
+ "reproduce these data using the same methods. We will also try to go\n",
+ "beyond the second-order polynomials metioned above and explore \n",
+ "which polynomial fits the data best.\n",
+ "\n",
+ "\n",
+ "The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from mpl_toolkits.mplot3d import Axes3D\n",
+ "import matplotlib.pyplot as plt\n",
+ "from matplotlib import cm\n",
+ "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
+ "import numpy as np\n",
+ "from random import random, seed\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.gca(projection='3d')\n",
+ "\n",
+ "# Make data.\n",
+ "x = np.arange(0, 1, 0.05)\n",
+ "y = np.arange(0, 1, 0.05)\n",
+ "x, y = np.meshgrid(x,y)\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ " term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ " term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ " term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ " term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ " return term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "z = FrankeFunction(x, y)\n",
+ "\n",
+ "# Plot the surface.\n",
+ "surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n",
+ " linewidth=0, antialiased=False)\n",
+ "\n",
+ "# Customize the z axis.\n",
+ "ax.set_zlim(-0.10, 1.40)\n",
+ "ax.zaxis.set_major_locator(LinearLocator(10))\n",
+ "ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n",
+ "\n",
+ "# Add a color bar which maps values to colors.\n",
+ "fig.colorbar(surf, shrink=0.5, aspect=5)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Exercise: Ordinary Least Square (OLS) on the Franke function\n",
+ "\n",
+ "We will generate our own dataset for a function\n",
+ "$\\mathrm{FrankeFunction}(x,y)$ with $x,y \\in [0,1]$. The function\n",
+ "$f(x,y)$ is the Franke function. You should explore also the addition\n",
+ "of an added stochastic noise to this function using the normal\n",
+ "distribution $N(0,1)$.\n",
+ "\n",
+ "*Write your own code* (using either a matrix inversion or a singular\n",
+ "value decomposition from e.g., **numpy** ) or use your code from\n",
+ "homeworks 1 and 2 and perform a standard least square regression\n",
+ "analysis using polynomials in $x$ and $y$ up to fifth order. Find the\n",
+ "[confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) of the parameters (estimators) $\\beta$ by computing their\n",
+ "variances, evaluate the Mean Squared error (MSE)"
+ ]
+ },
+ {
+ "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. If $\\tilde{\\hat{y}}_i$ is the predicted\n",
+ "value of the $i-th$ sample and $y_i$ is the corresponding true value,\n",
+ "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": [
+ "Your code has to include a scaling of the data (for example by\n",
+ "subtracting the mean value), and\n",
+ "a split of the data in training and test data. For this exercise you can\n",
+ "either write your own code or use for example the function for\n",
+ "splitting training data provided by the library **Scikit-Learn** (make\n",
+ "sure you have installed it). This function is called\n",
+ "$train\\_test\\_split$. **You should present a critical discussion of why and how you have scaled or not scaled the data**.\n",
+ "\n",
+ "It is normal in essentially all Machine Learning studies to split the\n",
+ "data in a training set and a test set (eventually also an additional\n",
+ "validation set). There\n",
+ "is no explicit recipe for how much data should be included as training\n",
+ "data and say test data. An accepted rule of thumb is to use\n",
+ "approximately $2/3$ to $4/5$ of the data as training data.\n",
+ "\n",
+ "\n",
+ "You can easily reuse the solutions to your exercises from week 35 and week 36.\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Exercise: Bias-variance trade-off and resampling techniques\n",
+ "\n",
+ "Our aim here is to study the bias-variance trade-off by implementing the **bootstrap** resampling technique.\n",
+ "\n",
+ "With a code which does OLS and includes resampling techniques, \n",
+ "we will now discuss the bias-variance trade-off in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks and basically all Machine Learning algorithms. \n",
+ "\n",
+ "Before you perform an analysis of the bias-variance trade-off on your test data, make\n",
+ "first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and\n",
+ "Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to \n",
+ "indicate possible regions of low/high bias and variance. You will most likely not get an\n",
+ "equally smooth curve!\n",
+ "\n",
+ "With this result we move on to the bias-variance trade-off analysis.\n",
+ "\n",
+ "Consider a\n",
+ "dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$.\n",
+ "\n",
+ "Let us assume that the true data is generated from a noisy model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here $\\epsilon$ is normally distributed with mean zero and standard\n",
+ "deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$.\n",
+ "\n",
+ "The parameters $\\boldsymbol{\\beta}$ are in turn found by optimizing the means\n",
+ "squared error via the so-called cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here the expected value $\\mathbb{E}$ is the sample value. \n",
+ "\n",
+ "Show that you can rewrite this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Explain what the terms mean, which one is the bias and which one is\n",
+ "the variance and discuss their interpretations.\n",
+ "\n",
+ "Perform then a bias-variance analysis of the Franke function by\n",
+ "studying the MSE value as function of the complexity of your model.\n",
+ "\n",
+ "Discuss the bias and variance trade-off as function\n",
+ "of your model complexity (the degree of the polynomial) and the number\n",
+ "of data points, and possibly also your training and test data using the **bootstrap** resampling method.\n",
+ "\n",
+ "Note also that when you calculate the bias, in all applications you don't know the function values $f_i$. You would hence replace them with the actual data points $y_i$.\n",
+ "\n",
+ "\n",
+ "### Exercise: Cross-validation as resampling techniques, adding more complexity\n",
+ "\n",
+ "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.\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 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\n",
+ "you got from your **bootstrap** code. Comment your results. Try $5-10$\n",
+ "folds. You can also compare your own cross-validation code with the\n",
+ "one provided by **Scikit-Learn**.\n",
+ "\n",
+ "\n",
+ "### Exercise: Ridge Regression on the Franke function with resampling\n",
+ "\n",
+ "Write your own code for the Ridge method, either using matrix\n",
+ "inversion or the singular value decomposition as done in the previous\n",
+ "exercise. Perform the same bootstrap analysis as in the\n",
+ "Exercise 2 (for the same polynomials) and the cross-validation in exercise 3 but now for different values of $\\lambda$. Compare and\n",
+ "analyze your results with those obtained in exercises 1-3. Study the\n",
+ "dependence on $\\lambda$.\n",
+ "\n",
+ "Study also the bias-variance trade-off as function of various values of\n",
+ "the parameter $\\lambda$. For the bias-variance trade-off, use the **bootstrap** resampling method. Comment your results. \n",
+ "\n",
+ "### Exercise: Lasso Regression on the Franke function with resampling\n",
+ "\n",
+ "This exercise is essentially a repeat of the previous two ones, but now\n",
+ "with Lasso regression. Write either your own code (difficult and optional) or, in this case,\n",
+ "you can also use the functionalities of **Scikit-Learn** (recommended). \n",
+ "Give a\n",
+ "critical discussion of the three methods and a judgement of which\n",
+ "model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the **bootstrap** resampling technique and an analysis of the mean squared error using cross-validation. \n",
+ "\n",
+ "### Exercise: Analysis of real data\n",
+ "\n",
+ "With our codes functioning and having been tested properly on a\n",
+ "simpler function we are now ready to look at real data. We will\n",
+ "essentially repeat in this exercise what was done in exercises 1-5. However, we\n",
+ "need first to download the data and prepare properly the inputs to our\n",
+ "codes. We are going to download digital terrain data from the website\n",
+ ",\n",
+ "\n",
+ "Or, if you prefer, we have placed selected datafiles at \n",
+ "\n",
+ "In order to obtain data for a specific region, you need to register as\n",
+ "a user (free) at this website and then decide upon which area you want\n",
+ "to fetch the digital terrain data from. In order to be able to read\n",
+ "the data properly, you need to specify that the format should be **SRTM\n",
+ "Arc-Second Global** and download the data as a **GeoTIF** file. The\n",
+ "files are then stored in *tif* format which can be imported into a\n",
+ "Python program using"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "scipy.misc.imread"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here is a simple part of a Python code which reads and plots the data\n",
+ "from such files"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "import numpy as np\n",
+ "from imageio import imread\n",
+ "import matplotlib.pyplot as plt\n",
+ "from mpl_toolkits.mplot3d import Axes3D\n",
+ "from matplotlib import cm\n",
+ "\n",
+ "# Load the terrain\n",
+ "terrain1 = imread('SRTM_data_Norway_1.tif')\n",
+ "# Show the terrain\n",
+ "plt.figure()\n",
+ "plt.title('Terrain over Norway 1')\n",
+ "plt.imshow(terrain1, cmap='gray')\n",
+ "plt.xlabel('X')\n",
+ "plt.ylabel('Y')\n",
+ "plt.show()\n",
+ "\"\"\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If you should have problems in downloading the digital terrain data,\n",
+ "we provide two examples under the data folder of project 1. One is\n",
+ "from a region close to Stavanger in Norway and the other Møsvatn\n",
+ "Austfjell, again in Norway.\n",
+ "Feel free to produce your own terrain data.\n",
+ "\n",
+ "\n",
+ "Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example [kaggle.com](https://www.kaggle.com/datasets) for examples.\n",
+ "\n",
+ "\n",
+ "Our final part deals with the parameterization of your digital terrain\n",
+ "data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial\n",
+ "approximation and cross-validation as resampling technique to evaluate which\n",
+ "model fits the data best.\n",
+ "\n",
+ "At the end, you should present a critical evaluation of your results\n",
+ "and discuss the applicability of these regression methods to the type\n",
+ "of data presented here (either the terrain data we propose or other data sets)."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter4.ipynb b/doc/LectureNotes/_build/html/_sources/chapter4.ipynb
new file mode 100644
index 000000000..faee62767
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter4.ipynb
@@ -0,0 +1,912 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Logistic Regression\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Logistic Regression\n",
+ "\n",
+ "In linear regression our main interest was centered on learning the\n",
+ "coefficients of a functional fit (say a polynomial) in order to be\n",
+ "able to predict the response of a continuous variable on some unseen\n",
+ "data. The fit to the continuous variable $y_i$ is based on some\n",
+ "independent variables $x_i$. Linear regression resulted in\n",
+ "analytical expressions for standard ordinary Least Squares or Ridge\n",
+ "regression (in terms of matrices to invert) for several quantities,\n",
+ "ranging from the variance and thereby the confidence intervals of the\n",
+ "optimal parameters $\\hat{\\beta}$ to the mean squared error. If we can invert\n",
+ "the product of the design matrices, linear regression gives then a\n",
+ "simple recipe for fitting our data.\n",
+ "\n",
+ "\n",
+ "Classification problems, however, are concerned with outcomes taking\n",
+ "the form of discrete variables (i.e. categories). We may for example,\n",
+ "on the basis of DNA sequencing for a number of patients, like to find\n",
+ "out which mutations are important for a certain disease; or based on\n",
+ "scans of various patients' brains, figure out if there is a tumor or\n",
+ "not; or given a specific physical system, we'd like to identify its\n",
+ "state, say whether it is an ordered or disordered system (typical\n",
+ "situation in solid state physics); or classify the status of a\n",
+ "patient, whether she/he has a stroke or not and many other similar\n",
+ "situations.\n",
+ "\n",
+ "The most common situation we encounter when we apply logistic\n",
+ "regression is that of two possible outcomes, normally denoted as a\n",
+ "binary outcome, true or false, positive or negative, success or\n",
+ "failure etc.\n",
+ "\n",
+ "\n",
+ "Logistic regression will also serve as our stepping stone towards\n",
+ "neural network algorithms and supervised deep learning. For logistic\n",
+ "learning, the minimization of the cost function leads to a non-linear\n",
+ "equation in the parameters $\\hat{\\beta}$. The optimization of the\n",
+ "problem calls therefore for minimization algorithms. This forms the\n",
+ "bottle neck of all machine learning algorithms, namely how to find\n",
+ "reliable minima of a multi-variable function. This leads us to the\n",
+ "family of gradient descent methods. The latter are the working horses\n",
+ "of basically all modern machine learning algorithms.\n",
+ "\n",
+ "We note also that many of the topics discussed here on logistic \n",
+ "regression are also commonly used in modern supervised Deep Learning\n",
+ "models, as we will see later.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Basics\n",
+ "\n",
+ "We consider the case where the dependent variables, also called the\n",
+ "responses or the outcomes, $y_i$ are discrete and only take values\n",
+ "from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n",
+ "\n",
+ "The goal is to predict the\n",
+ "output classes from the design matrix $\\boldsymbol{X}\\in\\mathbb{R}^{n\\times p}$\n",
+ "made of $n$ samples, each of which carries $p$ features or predictors. The\n",
+ "primary goal is to identify the classes to which new unseen samples\n",
+ "belong.\n",
+ "\n",
+ "Let us specialize to the case of two classes only, with outputs\n",
+ "$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a\n",
+ "credit card user that could default or not on her/his credit card\n",
+ "debt. That is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before moving to the logistic model, let us try to use our linear\n",
+ "regression model to classify these two outcomes. We could for example\n",
+ "fit a linear model to the default case if $y_i > 0.5$ and the no\n",
+ "default case $y_i \\leq 0.5$.\n",
+ "\n",
+ "We would then have our \n",
+ "weighted linear combination, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{y}$ is a vector representing the possible outcomes, $\\boldsymbol{X}$ is our\n",
+ "$n\\times p$ design matrix and $\\boldsymbol{\\beta}$ represents our estimators/predictors.\n",
+ "\n",
+ "\n",
+ "The main problem with our function is that it takes values on the\n",
+ "entire real axis. In the case of logistic regression, however, the\n",
+ "labels $y_i$ are discrete variables. A typical example is the credit\n",
+ "card data discussed below here, where we can set the state of\n",
+ "defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons\n",
+ "in the data set (see the full example below).\n",
+ "\n",
+ "One simple way to get a discrete output is to have sign\n",
+ "functions that map the output of a linear regressor to values $\\{0,1\\}$,\n",
+ "$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n",
+ "We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron\" model in the machine learning\n",
+ "literature. This model is extremely simple. However, in many cases it is more\n",
+ "favorable to use a ``soft\" classifier that outputs\n",
+ "the probability of a given category. This leads us to the logistic function.\n",
+ "\n",
+ "\n",
+ "The following example on data for coronary heart disease (CHD) as function of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from IPython.display import display\n",
+ "from pylab import plt, mpl\n",
+ "plt.style.use('seaborn')\n",
+ "mpl.rcParams['font.family'] = 'serif'\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"chddata.csv\"),'r')\n",
+ "\n",
+ "# Read the chd data as csv file and organize the data into arrays with age group, age, and chd\n",
+ "chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))\n",
+ "chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']\n",
+ "output = chd['CHD']\n",
+ "age = chd['Age']\n",
+ "agegroup = chd['Agegroup']\n",
+ "numberID = chd['ID'] \n",
+ "display(chd)\n",
+ "\n",
+ "plt.scatter(age, output, marker='o')\n",
+ "plt.axis([18,70.0,-0.1, 1.2])\n",
+ "plt.xlabel(r'Age')\n",
+ "plt.ylabel(r'CHD')\n",
+ "plt.title(r'Age distribution and Coronary heart disease')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What we could attempt however is to plot the mean value for each group."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "agegroupmean = np.array([0.1, 0.133, 0.250, 0.333, 0.462, 0.625, 0.765, 0.800])\n",
+ "group = np.array([1, 2, 3, 4, 5, 6, 7, 8])\n",
+ "plt.plot(group, agegroupmean, \"r-\")\n",
+ "plt.axis([0,9,0, 1.0])\n",
+ "plt.xlabel(r'Age group')\n",
+ "plt.ylabel(r'CHD mean values')\n",
+ "plt.title(r'Mean values for each age group')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We are now trying to find a function $f(y\\vert x)$, that is a function which gives us an expected value for the output $y$ with a given input $x$.\n",
+ "In standard linear regression with a linear dependence on $x$, we would write this in terms of our model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(y_i\\vert x_i)=\\beta_0+\\beta_1 x_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This expression implies however that $f(y_i\\vert x_i)$ could take any\n",
+ "value from minus infinity to plus infinity. If we however let\n",
+ "$f(y\\vert y)$ be represented by the mean value, the above example\n",
+ "shows us that we can constrain the function to take values between\n",
+ "zero and one, that is we have $0 \\le f(y_i\\vert x_i) \\le 1$. Looking\n",
+ "at our last curve we see also that it has an S-shaped form. This leads\n",
+ "us to a very popular model for the function $f$, namely the so-called\n",
+ "Sigmoid function or logistic model. We will consider this function as\n",
+ "representing the probability for finding a value of $y_i$ with a given\n",
+ "$x_i$.\n",
+ "\n",
+ "\n",
+ "## The logistic function\n",
+ "\n",
+ "Another widely studied model, is the so-called \n",
+ "perceptron model, which is an example of a \"hard classification\" model. We\n",
+ "will encounter this model when we discuss neural networks as\n",
+ "well. Each datapoint is deterministically assigned to a category (i.e\n",
+ "$y_i=0$ or $y_i=1$). In many cases, and the coronary heart disease data forms one of many such examples, it is favorable to have a \"soft\"\n",
+ "classifier that outputs the probability of a given category rather\n",
+ "than a single value. For example, given $x_i$, the classifier\n",
+ "outputs the probability of being in a category $k$. Logistic regression\n",
+ "is the most common example of a so-called soft classifier. In logistic\n",
+ "regression, the probability that a data point $x_i$\n",
+ "belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that $1-p(t)= p(-t)$.\n",
+ "\n",
+ "## Examples of likelihood functions used in logistic regression and nueral networks\n",
+ "\n",
+ "\n",
+ "The following code plots the logistic function, the step function and other functions we will encounter from here and on."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"The sigmoid function (or the logistic curve) is a\n",
+ "function that takes any real number, z, and outputs a number (0,1).\n",
+ "It is useful in neural networks for assigning weights on a relative scale.\n",
+ "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n",
+ "\n",
+ "import numpy\n",
+ "import matplotlib.pyplot as plt\n",
+ "import math as mt\n",
+ "\n",
+ "z = numpy.arange(-5, 5, .1)\n",
+ "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n",
+ "sigma = sigma_fn(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, sigma)\n",
+ "ax.set_ylim([-0.1, 1.1])\n",
+ "ax.set_xlim([-5,5])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('sigmoid function')\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\"\"\"Step Function\"\"\"\n",
+ "z = numpy.arange(-5, 5, .02)\n",
+ "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n",
+ "step = step_fn(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, step)\n",
+ "ax.set_ylim([-0.5, 1.5])\n",
+ "ax.set_xlim([-5,5])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('step function')\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\"\"\"tanh Function\"\"\"\n",
+ "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n",
+ "t = numpy.tanh(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, t)\n",
+ "ax.set_ylim([-1.0, 1.0])\n",
+ "ax.set_xlim([-2*mt.pi,2*mt.pi])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('tanh function')\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "p(y_i=1|x_i,\\boldsymbol{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n",
+ "p(y_i=0|x_i,\\boldsymbol{\\beta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\beta}),\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n",
+ "\n",
+ "Note that we used"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(y_i=0\\vert x_i, \\boldsymbol{\\beta}) = 1-p(y_i=1\\vert x_i, \\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In order to define the total likelihood for all possible outcomes from a \n",
+ "dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n",
+ "$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n",
+ "We aim thus at maximizing \n",
+ "the probability of seeing the observed data. We can then approximate the \n",
+ "likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "P(\\mathcal{D}|\\boldsymbol{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\boldsymbol{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\boldsymbol{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "from which we obtain the log-likelihood and our **cost/loss** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\boldsymbol{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\boldsymbol{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\boldsymbol{\\beta}))\\right]\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Reordering the logarithms, we can rewrite the **cost/loss** function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\boldsymbol{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n",
+ "Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathcal{C}(\\boldsymbol{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n",
+ "in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.\n",
+ "\n",
+ "\n",
+ "The cross entropy is a convex function of the weights $\\boldsymbol{\\beta}$ and,\n",
+ "therefore, any local minimizer is a global minimizer. \n",
+ "\n",
+ "\n",
+ "Minimizing this\n",
+ "cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us now define a vector $\\boldsymbol{y}$ with $n$ elements $y_i$, an\n",
+ "$n\\times p$ matrix $\\boldsymbol{X}$ which contains the $x_i$ values and a\n",
+ "vector $\\boldsymbol{p}$ of fitted probabilities $p(y_i\\vert x_i,\\boldsymbol{\\beta})$. We can rewrite in a more compact form the first\n",
+ "derivative of cost function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n",
+ "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\log{ \\frac{p(\\boldsymbol{\\beta}\\boldsymbol{x})}{1-p(\\boldsymbol{\\beta}\\boldsymbol{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we defined $\\boldsymbol{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\boldsymbol{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\boldsymbol{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Till now we have mainly focused on two classes, the so-called binary\n",
+ "system. Suppose we wish to extend to $K$ classes. Let us for the sake\n",
+ "of simplicity assume we have only two predictors. We have then following model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\log{\\frac{p(C=1\\vert x)}{p(K\\vert x)}} = \\beta_{10}+\\beta_{11}x_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and so on till the class $C=K-1$ class"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the model is specified in term of $K-1$ so-called log-odds or\n",
+ "**logit** transformations.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our discussion of neural networks we will encounter the above again\n",
+ "in terms of a slightly modified function, the so-called **Softmax** function.\n",
+ "\n",
+ "The softmax function is used in various multiclass classification\n",
+ "methods, such as multinomial logistic regression (also known as\n",
+ "softmax regression), multiclass linear discriminant analysis, naive\n",
+ "Bayes classifiers, and artificial neural networks. Specifically, in\n",
+ "multinomial logistic regression and linear discriminant analysis, the\n",
+ "input to the function is the result of $K$ distinct linear functions,\n",
+ "and the predicted probability for the $k$-th class given a sample\n",
+ "vector $\\boldsymbol{x}$ and a weighting vector $\\boldsymbol{\\beta}$ is (with two\n",
+ "predictors):"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is easy to extend to more predictors. The final class is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and they sum to one. Our earlier discussions were all specialized to\n",
+ "the case with two classes only. It is easy to see from the above that\n",
+ "what we derived earlier is compatible with these equations.\n",
+ "\n",
+ "To find the optimal parameters we would typically use a gradient\n",
+ "descent method. Newton's method and gradient descent methods are\n",
+ "discussed in the material on [optimization\n",
+ "methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n",
+ "\n",
+ "## Wisconsin Cancer Data\n",
+ "\n",
+ "We show here how we can use a simple regression case on the breast\n",
+ "cancer data using Logistic regression as our algorithm for\n",
+ "classification."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "# Logistic Regression\n",
+ "logreg = LogisticRegression(solver='lbfgs')\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# Logistic Regression\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In addition to the above scores, we could also study the covariance (and the correlation matrix).\n",
+ "We use **Pandas** to compute the correlation matrix."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "cancer = load_breast_cancer()\n",
+ "import pandas as pd\n",
+ "# Making a data frame\n",
+ "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n",
+ "\n",
+ "fig, axes = plt.subplots(15,2,figsize=(10,20))\n",
+ "malignant = cancer.data[cancer.target == 0]\n",
+ "benign = cancer.data[cancer.target == 1]\n",
+ "ax = axes.ravel()\n",
+ "\n",
+ "for i in range(30):\n",
+ " _, bins = np.histogram(cancer.data[:,i], bins =50)\n",
+ " ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n",
+ " ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n",
+ " ax[i].set_title(cancer.feature_names[i])\n",
+ " ax[i].set_yticks(())\n",
+ "ax[0].set_xlabel(\"Feature magnitude\")\n",
+ "ax[0].set_ylabel(\"Frequency\")\n",
+ "ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n",
+ "fig.tight_layout()\n",
+ "plt.show()\n",
+ "\n",
+ "import seaborn as sns\n",
+ "correlation_matrix = cancerpd.corr().round(1)\n",
+ "# use the heatmap function from seaborn to plot the correlation matrix\n",
+ "# annot = True to print the values inside the square\n",
+ "plt.figure(figsize=(15,8))\n",
+ "sns.heatmap(data=correlation_matrix, annot=True)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example we note two things. In the first plot we display\n",
+ "the overlap of benign and malignant tumors as functions of the various\n",
+ "features in the Wisconsing breast cancer data set. We see that for\n",
+ "some of the features we can distinguish clearly the benign and\n",
+ "malignant cases while for other features we cannot. This can point to\n",
+ "us which features may be of greater interest when we wish to classify\n",
+ "a benign or not benign tumour.\n",
+ "\n",
+ "In the second figure we have computed the so-called correlation\n",
+ "matrix, which in our case with thirty features becomes a $30\\times 30$\n",
+ "matrix.\n",
+ "\n",
+ "We constructed this matrix using **pandas** via the statements"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and then"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "correlation_matrix = cancerpd.corr().round(1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Diagonalizing this matrix we can in turn say something about which\n",
+ "features are of relevance and which are not. This leads us to\n",
+ "the classical Principal Component Analysis (PCA) theorem with\n",
+ "applications. This will be discussed later this semester ([week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html))."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "# Logistic Regression\n",
+ "logreg = LogisticRegression(solver='lbfgs')\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# Logistic Regression\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "\n",
+ "from sklearn.preprocessing import LabelEncoder\n",
+ "from sklearn.model_selection import cross_validate\n",
+ "#Cross validation\n",
+ "accuracy = cross_validate(logreg,X_test_scaled,y_test,cv=10)['test_score']\n",
+ "print(accuracy)\n",
+ "print(\"Test set accuracy with Logistic Regression and scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "\n",
+ "import scikitplot as skplt\n",
+ "y_pred = logreg.predict(X_test_scaled)\n",
+ "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
+ "plt.show()\n",
+ "y_probas = logreg.predict_proba(X_test_scaled)\n",
+ "skplt.metrics.plot_roc(y_test, y_probas)\n",
+ "plt.show()\n",
+ "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
+ "plt.show()"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter5.ipynb b/doc/LectureNotes/_build/html/_sources/chapter5.ipynb
new file mode 100644
index 000000000..0e24adf4e
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter5.ipynb
@@ -0,0 +1,1867 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Support Vector Machines, overarching aims\n",
+ "\n",
+ "A Support Vector Machine (SVM) is a very powerful and versatile\n",
+ "Machine Learning method, capable of performing linear or nonlinear\n",
+ "classification, regression, and even outlier detection. It is one of\n",
+ "the most popular models in Machine Learning, and anyone interested in\n",
+ "Machine Learning should have it in their toolbox. SVMs are\n",
+ "particularly well suited for classification of complex but small-sized or\n",
+ "medium-sized datasets. \n",
+ "\n",
+ "The case with two well-separated classes only can be understood in an\n",
+ "intuitive way in terms of lines in a two-dimensional space separating\n",
+ "the two classes (see figure below).\n",
+ "\n",
+ "The basic mathematics behind the SVM is however less familiar to most of us. \n",
+ "It relies on the definition of hyperplanes and the\n",
+ "definition of a **margin** which separates classes (in case of\n",
+ "classification problems) of variables. It is also used for regression\n",
+ "problems.\n",
+ "\n",
+ "With SVMs we distinguish between hard margin and soft margins. The\n",
+ "latter introduces a so-called softening parameter to be discussed\n",
+ "below. We distinguish also between linear and non-linear\n",
+ "approaches. The latter are the most frequent ones since it is rather\n",
+ "unlikely that we can separate classes easily by say straight lines.\n",
+ "\n",
+ "\n",
+ "## Hyperplanes and all that\n",
+ "\n",
+ "The theory behind support vector machines (SVM hereafter) is based on\n",
+ "the mathematical description of so-called hyperplanes. Let us start\n",
+ "with a two-dimensional case. This will also allow us to introduce our\n",
+ "first SVM examples. These will be tailored to the case of two specific\n",
+ "classes, as displayed in the figure here based on the usage of the petal data.\n",
+ "\n",
+ "We assume here that our data set can be well separated into two\n",
+ "domains, where a straight line does the job in the separating the two\n",
+ "classes. Here the two classes are represented by either squares or\n",
+ "circles."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "from sklearn import datasets\n",
+ "from sklearn.svm import SVC, LinearSVC\n",
+ "from sklearn.linear_model import SGDClassifier\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import matplotlib\n",
+ "import matplotlib.pyplot as plt\n",
+ "plt.rcParams['axes.labelsize'] = 14\n",
+ "plt.rcParams['xtick.labelsize'] = 12\n",
+ "plt.rcParams['ytick.labelsize'] = 12\n",
+ "\n",
+ "\n",
+ "iris = datasets.load_iris()\n",
+ "X = iris[\"data\"][:, (2, 3)] # petal length, petal width\n",
+ "y = iris[\"target\"]\n",
+ "\n",
+ "setosa_or_versicolor = (y == 0) | (y == 1)\n",
+ "X = X[setosa_or_versicolor]\n",
+ "y = y[setosa_or_versicolor]\n",
+ "\n",
+ "\n",
+ "\n",
+ "C = 5\n",
+ "alpha = 1 / (C * len(X))\n",
+ "\n",
+ "lin_clf = LinearSVC(loss=\"hinge\", C=C, random_state=42)\n",
+ "svm_clf = SVC(kernel=\"linear\", C=C)\n",
+ "sgd_clf = SGDClassifier(loss=\"hinge\", learning_rate=\"constant\", eta0=0.001, alpha=alpha,\n",
+ " max_iter=100000, random_state=42)\n",
+ "\n",
+ "scaler = StandardScaler()\n",
+ "X_scaled = scaler.fit_transform(X)\n",
+ "\n",
+ "lin_clf.fit(X_scaled, y)\n",
+ "svm_clf.fit(X_scaled, y)\n",
+ "sgd_clf.fit(X_scaled, y)\n",
+ "\n",
+ "print(\"LinearSVC: \", lin_clf.intercept_, lin_clf.coef_)\n",
+ "print(\"SVC: \", svm_clf.intercept_, svm_clf.coef_)\n",
+ "print(\"SGDClassifier(alpha={:.5f}):\".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)\n",
+ "\n",
+ "# Compute the slope and bias of each decision boundary\n",
+ "w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]\n",
+ "b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]\n",
+ "w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]\n",
+ "b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]\n",
+ "w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]\n",
+ "b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]\n",
+ "\n",
+ "# Transform the decision boundary lines back to the original scale\n",
+ "line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])\n",
+ "line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])\n",
+ "line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])\n",
+ "\n",
+ "# Plot all three decision boundaries\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.plot(line1[:, 0], line1[:, 1], \"k:\", label=\"LinearSVC\")\n",
+ "plt.plot(line2[:, 0], line2[:, 1], \"b--\", linewidth=2, label=\"SVC\")\n",
+ "plt.plot(line3[:, 0], line3[:, 1], \"r-\", label=\"SGDClassifier\")\n",
+ "plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\") # label=\"Iris-Versicolor\"\n",
+ "plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\") # label=\"Iris-Setosa\"\n",
+ "plt.xlabel(\"Petal length\", fontsize=14)\n",
+ "plt.ylabel(\"Petal width\", fontsize=14)\n",
+ "plt.legend(loc=\"upper center\", fontsize=14)\n",
+ "plt.axis([0, 5.5, 0, 2])\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The aim of the SVM algorithm is to find a hyperplane in a\n",
+ "$p$-dimensional space, where $p$ is the number of features that\n",
+ "distinctly classifies the data points.\n",
+ "\n",
+ "In a $p$-dimensional space, a hyperplane is what we call an affine subspace of dimension of $p-1$.\n",
+ "As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is \n",
+ "a two-dimensional subspace, or stated simply, a plane. \n",
+ "\n",
+ "In two dimensions, with the variables $x_1$ and $x_2$, the hyperplane is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b+w_1x_1+w_2x_2=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line \n",
+ "$b+w_1x_1+w_2x_2=0$. \n",
+ "In two dimensions we define the vectors $\\boldsymbol{x} =[x1,x2]$ and $\\boldsymbol{w}=[w1,w2]$. \n",
+ "We can then rewrite the above equation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}^T\\boldsymbol{w}+b=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \\pm 1$. \n",
+ "In a $p$-dimensional space of say $p$ features we have a hyperplane defines as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b+wx_1+w_2x_2+\\dots +w_px_p=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we define a \n",
+ "matrix $\\boldsymbol{X}=\\left[\\boldsymbol{x}_1,\\boldsymbol{x}_2,\\dots, \\boldsymbol{x}_p\\right]$\n",
+ "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 $\\boldsymbol{X}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i = \\begin{bmatrix} x_{i1} \\\\ x_{i2} \\\\ \\dots \\\\ \\dots \\\\ x_{ip} \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If the above condition is not met for a given vector $\\boldsymbol{x}_i$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} >0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "if our output $y_i=1$.\n",
+ "In this case we say that $\\boldsymbol{x}_i$ lies on one of the sides of the hyperplane and if"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} < 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for the class of observations $y_i=-1$, \n",
+ "then $\\boldsymbol{x}_i$ lies on the other side. \n",
+ "\n",
+ "Equivalently, for the two classes of observations we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i\\left(b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip}\\right) > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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.\n",
+ "\n",
+ "\n",
+ "### The two-dimensional case\n",
+ "\n",
+ "Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional\n",
+ "plane. To separate the two classes of data points, there are many\n",
+ "possible lines (hyperplanes if you prefer a more strict naming) \n",
+ "that could be chosen. Our objective is to find a\n",
+ "plane that has the maximum margin, i.e the maximum distance between\n",
+ "data points of both classes. Maximizing the margin distance provides\n",
+ "some reinforcement so that future data points can be classified with\n",
+ "more confidence.\n",
+ "\n",
+ "What a linear classifier attempts to accomplish is to split the\n",
+ "feature space into two half spaces by placing a hyperplane between the\n",
+ "data points. This hyperplane will be our decision boundary. All\n",
+ "points on one side of the plane will belong to class one and all points\n",
+ "on the other side of the plane will belong to the second class two.\n",
+ "\n",
+ "Unfortunately there are many ways in which we can place a hyperplane\n",
+ "to divide the data. Below is an example of two candidate hyperplanes\n",
+ "for our data sample.\n",
+ "\n",
+ "\n",
+ "Let us define the function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(x) = \\boldsymbol{w}^T\\boldsymbol{x}+b = 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "as the function that determines the line $L$ that separates two classes (our two features), see the figure here. \n",
+ "\n",
+ "\n",
+ "Any point defined by $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_2$ on the line $L$ will satisfy $\\boldsymbol{w}^T(\\boldsymbol{x}_1-\\boldsymbol{x}_2)=0$. \n",
+ "\n",
+ "The signed distance $\\delta$ from any point defined by a vector $\\boldsymbol{x}$ and a point $\\boldsymbol{x}_0$ on the line $L$ is then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta = \\frac{1}{\\vert\\vert \\boldsymbol{w}\\vert\\vert}(\\boldsymbol{w}^T\\boldsymbol{x}+b).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How do we find the parameter $b$ and the vector $\\boldsymbol{w}$? What we could\n",
+ "do is to define a cost function which now contains the set of all\n",
+ "misclassified points $M$ and attempt to minimize this function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{w},b) = -\\sum_{i\\in M} y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could now for example define all values $y_i =1$ as misclassified in case we have $\\boldsymbol{w}^T\\boldsymbol{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C}{\\partial b} = -\\sum_{i\\in M} y_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C}{\\partial \\boldsymbol{w}} = -\\sum_{i\\in M} y_ix_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b \\leftarrow b +\\eta \\frac{\\partial C}{\\partial b},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{w} \\leftarrow \\boldsymbol{w} +\\eta \\frac{\\partial C}{\\partial \\boldsymbol{w}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\eta$ is our by now well-known learning rate. \n",
+ "\n",
+ "\n",
+ "\n",
+ "The equations we discussed above can be coded rather easily (the\n",
+ "framework is similar to what we developed for logistic\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There are however problems with this approach, although it looks\n",
+ "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.\n",
+ "\n",
+ "\n",
+ "For small\n",
+ "gaps between the entries, we may also end up needing many iterations\n",
+ "before the solutions converge and if the data cannot be separated\n",
+ "properly into two distinct classes, we may not experience a converge\n",
+ "at all.\n",
+ "\n",
+ "\n",
+ "### A better approach\n",
+ "\n",
+ "A better approach is rather to try to define a large margin between\n",
+ "the two classes (if they are well separated from the beginning).\n",
+ "\n",
+ "Thus, we wish to find a margin $M$ with $\\boldsymbol{w}$ normalized to\n",
+ "$\\vert\\vert \\boldsymbol{w}\\vert\\vert =1$ subject to the condition"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, p.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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. \n",
+ "\n",
+ "We seek thus the largest value $M$ defined by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{1}{\\vert \\vert \\boldsymbol{w}\\vert\\vert}y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, n,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M\\vert \\vert \\boldsymbol{w}\\vert\\vert \\hspace{0.1cm}\\forall i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we scale the equation so that $\\vert \\vert \\boldsymbol{w}\\vert\\vert = 1/M$, we have to find the minimum of \n",
+ "$\\boldsymbol{w}^T\\boldsymbol{w}=\\vert \\vert \\boldsymbol{w}\\vert\\vert$ (the norm) subject to the condition"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq 1 \\hspace{0.1cm}\\forall i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have thus defined our margin as the invers of the norm of\n",
+ "$\\boldsymbol{w}$. We want to minimize the norm in order to have a as large as\n",
+ "possible margin $M$. Before we proceed, we need to remind ourselves\n",
+ "about Lagrangian multipliers.\n",
+ "\n",
+ "\n",
+ "## A quick Reminder on Lagrangian Multipliers\n",
+ "\n",
+ "Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an\n",
+ "extreme we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "df=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A necessary and sufficient condition is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "due to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)\n",
+ "so that they are no longer all independent. It is possible at least in principle to use each \n",
+ "constraint to eliminate one variable\n",
+ "and to proceed with a new and smaller set of independent varables.\n",
+ "\n",
+ "The use of so-called Lagrangian multipliers is an alternative technique when the elimination\n",
+ "of variables is incovenient or undesirable. Assume that we have an equation of constraint on \n",
+ "the variables $x,y,z$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\phi(x,y,z) = 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "d\\phi = \\frac{\\partial \\phi}{\\partial x}dx+\\frac{\\partial \\phi}{\\partial y}dy+\\frac{\\partial \\phi}{\\partial z}dz =0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we cannot set anymore"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "if $df=0$ is wanted\n",
+ "because there are now only two independent variables! Assume $x$ and $y$ are the independent \n",
+ "variables.\n",
+ "Then $dz$ is no longer arbitrary.\n",
+ "\n",
+ "\n",
+ "However, we can add to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "a multiplum of $d\\phi$, viz. $\\lambda d\\phi$, resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "df+\\lambda d\\phi = (\\frac{\\partial f}{\\partial z}+\\lambda\n",
+ "\\frac{\\partial \\phi}{\\partial x})dx+(\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y})dy+\n",
+ "(\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z})dz =0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our multiplier is chosen so that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z} =0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial x}+\\lambda\\frac{\\partial \\phi}{\\partial x} =0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y} =0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and\n",
+ "$\\lambda$. Actually we want only $x,y,z$, $\\lambda$ needs not to be determined, \n",
+ "it is therefore often called\n",
+ "Lagrange's undetermined multiplier.\n",
+ "If we have a set of constraints $\\phi_k$ we have the equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial f}{\\partial x_i}+\\sum_k\\lambda_k\\frac{\\partial \\phi_k}{\\partial x_i} =0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In order to solve the above problem, we define the following Lagrangian function to be minimized"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}(\\lambda,b,\\boldsymbol{w})=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-1\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\\lambda_i \\geq 0$.\n",
+ "\n",
+ "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting these constraints into the equation for $\\cal{L}$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to the constraints $\\lambda_i\\geq 0$ and $\\sum_i\\lambda_iy_i=0$. \n",
+ "We must in addition satisfy the [Karush-Kuhn-Tucker](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions) (KKT) condition"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -1\\right] \\hspace{0.1cm}\\forall i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "1. If $\\lambda_i > 0$, then $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ and we say that $x_i$ is on the boundary.\n",
+ "\n",
+ "2. If $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\\lambda_i=0$. \n",
+ "\n",
+ "When $\\lambda_i > 0$, the vectors $\\boldsymbol{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$. \n",
+ "\n",
+ "\n",
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\\lambda$ the following problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1\\boldsymbol{x}_1^T\\boldsymbol{x}_1 & y_1y_2\\boldsymbol{x}_1^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_1^T\\boldsymbol{x}_n \\\\\n",
+ "y_2y_1\\boldsymbol{x}_2^T\\boldsymbol{x}_1 & y_2y_2\\boldsymbol{x}_2^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_2^T\\boldsymbol{x}_n \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "y_ny_1\\boldsymbol{x}_n^T\\boldsymbol{x}_1 & y_ny_2\\boldsymbol{x}_n^T\\boldsymbol{x}_2 & \\dots & \\dots & y_ny_n\\boldsymbol{x}_n^T\\boldsymbol{x}_n \\\\\n",
+ "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n",
+ "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Solving the above problem, yields the values of $\\lambda_i$.\n",
+ "To find the coefficients of your hyperplane we need simply to compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{w}=\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With our vector $\\boldsymbol{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b = \\frac{1}{y_i}-\\boldsymbol{w}^T\\boldsymbol{x}_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b = \\frac{1}{N_s}\\sum_{j\\in N_s}\\left(y_j-\\sum_{i=1}^n\\lambda_iy_i\\boldsymbol{x}_i^T\\boldsymbol{x}_j\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With our hyperplane coefficients we can use our classifier to assign any observation by simply using"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i = \\mathrm{sign}(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Below we discuss how to find the optimal values of $\\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier. \n",
+ "\n",
+ "\n",
+ "## A soft classifier\n",
+ "\n",
+ "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.\n",
+ "\n",
+ "Suppose now that classes overlap in feature space, as shown in the\n",
+ "figure here. One way to deal with this problem before we define the\n",
+ "so-called **kernel approach**, is to allow a kind of slack in the sense\n",
+ "that we allow some points to be on the wrong side of the margin.\n",
+ "\n",
+ "We introduce thus the so-called **slack** variables $\\boldsymbol{\\xi} =[\\xi_1,x_2,\\dots,x_n]$ and \n",
+ "modify our previous equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the requirement $\\xi_i\\geq 0$. The total violation is now $\\sum_i\\xi$. \n",
+ "The value $\\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction\n",
+ "$y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ is on the wrong side of its margin. Hence by bounding the sum $\\sum_i \\xi_i$,\n",
+ "we bound the total amount by which predictions fall on the wrong side of their margins.\n",
+ "\n",
+ "Misclassifications occur when $\\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of\n",
+ "misclassifications.\n",
+ "\n",
+ "\n",
+ "This has in turn the consequences that we change our optmization problem to finding the minimum of"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-(1-\\xi_)\\right]+C\\sum_{i=1}^n\\xi_i-\\sum_{i=1}^n\\gamma_i\\xi_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i \\hspace{0.1cm}\\forall i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the requirement $\\xi_i\\geq 0$.\n",
+ "\n",
+ "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lambda_i = C-\\gamma_i \\hspace{0.1cm}\\forall i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting these constraints into the equation for $\\cal{L}$ we obtain the same equation as before"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "but now subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ and $0\\leq\\lambda_i \\leq C$. \n",
+ "We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "5\n",
+ "0\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "M\n",
+ "A\n",
+ "T\n",
+ "H\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma_i\\xi_i = 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -(1-\\xi_) \\geq 0 \\hspace{0.1cm}\\forall i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Kernels and non-linearity\n",
+ "\n",
+ "The cases we have studied till now, were all characterized by two classes\n",
+ "with a close to linear separability. The classifiers we have described\n",
+ "so far find linear boundaries in our input feature space. It is\n",
+ "possible to make our procedure more flexible by exploring the feature\n",
+ "space using other basis expansions such as higher-order polynomials,\n",
+ "wavelets, splines etc.\n",
+ "\n",
+ "If our feature space is not easy to separate, as shown in the figure\n",
+ "here, we can achieve a better separation by introducing more complex\n",
+ "basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to \n",
+ "obtain a separation between the classes which is almost linear. \n",
+ "\n",
+ "The change of basis, from $x\\rightarrow z=\\phi(x)$ leads to the same type of equations to be solved, except that\n",
+ "we need to introduce for example a polynomial transformation to a two-dimensional training set."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import os\n",
+ "\n",
+ "np.random.seed(42)\n",
+ "\n",
+ "# To plot pretty figures\n",
+ "import matplotlib\n",
+ "import matplotlib.pyplot as plt\n",
+ "plt.rcParams['axes.labelsize'] = 14\n",
+ "plt.rcParams['xtick.labelsize'] = 12\n",
+ "plt.rcParams['ytick.labelsize'] = 12\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn import datasets\n",
+ "\n",
+ "\n",
+ "\n",
+ "X1D = np.linspace(-4, 4, 9).reshape(-1, 1)\n",
+ "X2D = np.c_[X1D, X1D**2]\n",
+ "y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plt.grid(True, which='both')\n",
+ "plt.axhline(y=0, color='k')\n",
+ "plt.plot(X1D[:, 0][y==0], np.zeros(4), \"bs\")\n",
+ "plt.plot(X1D[:, 0][y==1], np.zeros(5), \"g^\")\n",
+ "plt.gca().get_yaxis().set_ticks([])\n",
+ "plt.xlabel(r\"$x_1$\", fontsize=20)\n",
+ "plt.axis([-4.5, 4.5, -0.2, 0.2])\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plt.grid(True, which='both')\n",
+ "plt.axhline(y=0, color='k')\n",
+ "plt.axvline(x=0, color='k')\n",
+ "plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], \"bs\")\n",
+ "plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], \"g^\")\n",
+ "plt.xlabel(r\"$x_1$\", fontsize=20)\n",
+ "plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n",
+ "plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])\n",
+ "plt.plot([-4.5, 4.5], [6.5, 6.5], \"r--\", linewidth=3)\n",
+ "plt.axis([-4.5, 4.5, -1, 17])\n",
+ "plt.subplots_adjust(right=1)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "z = \\phi(x_i) =\\left(x_i^2, y_i^2, \\sqrt{2}x_iy_i\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{z}_i^T\\boldsymbol{z}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$, and for the support vectors"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_i(\\boldsymbol{w}^T\\boldsymbol{z}_i+b)= 1 \\hspace{0.1cm}\\forall i,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "from which we also find $b$.\n",
+ "To compute $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we define the kernel $K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\boldsymbol{z}_i^T\\boldsymbol{z}_j= \\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the above example, the kernel reads"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "K(\\boldsymbol{x}_i,\\boldsymbol{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.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note that this is nothing but the dot product of the two original\n",
+ "vectors $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$. Instead of thus computing the\n",
+ "product in the Lagrangian of $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we simply compute\n",
+ "the dot product $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$.\n",
+ "\n",
+ "\n",
+ "This leads to the so-called\n",
+ "kernel trick and the result leads to the same as if we went through\n",
+ "the trouble of performing the transformation\n",
+ "$\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j)$ during the SVM calculations.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using our definition of the kernel We can rewrite again the Lagrangian"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\cal{L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{z}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ in terms of a convex optimization problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n",
+ "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n",
+ "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n",
+ "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n",
+ "If we add the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n",
+ "\n",
+ "We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n",
+ " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\hspace{0.2cm} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Below we discuss how to solve these equations. Here we note that the matrix $\\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$.\n",
+ "Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$ leads to $f=0$ and $\\boldsymbol{A}=\\boldsymbol{y}$. How to set up the matrix $\\boldsymbol{G}$ is discussed later. Here note that the inequalities $0\\leq \\lambda_i \\leq C$ can be split up into\n",
+ "$0\\leq \\lambda_i$ and $\\lambda_i \\leq C$. These two inequalities define then the matrix $\\boldsymbol{G}$ and the vector $\\boldsymbol{h}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Different kernels and Mercer's theorem\n",
+ "\n",
+ "There are several popular kernels being used. These are\n",
+ "1. Linear: $K(\\boldsymbol{x},\\boldsymbol{y})=\\boldsymbol{x}^T\\boldsymbol{y}$,\n",
+ "\n",
+ "2. Polynomial: $K(\\boldsymbol{x},\\boldsymbol{y})=(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)^d$,\n",
+ "\n",
+ "3. Gaussian Radial Basis Function: $K(\\boldsymbol{x},\\boldsymbol{y})=\\exp{\\left(-\\gamma\\vert\\vert\\boldsymbol{x}-\\boldsymbol{y}\\vert\\vert^2\\right)}$,\n",
+ "\n",
+ "4. Tanh: $K(\\boldsymbol{x},\\boldsymbol{y})=\\tanh{(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)}$,\n",
+ "\n",
+ "and many other ones.\n",
+ "\n",
+ "An important theorem for us is [Mercer's\n",
+ "theorem](https://en.wikipedia.org/wiki/Mercer%27s_theorem). The\n",
+ "theorem states that if a kernel function $K$ is symmetric, continuous\n",
+ "and leads to a positive semi-definite matrix $\\boldsymbol{P}$ then there\n",
+ "exists a function $\\phi$ that maps $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_j$ into\n",
+ "another space (possibly with much higher dimensions) such that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So you can use $K$ as a kernel since you know $\\phi$ exists, even if\n",
+ "you don’t know what $\\phi$ is. \n",
+ "\n",
+ "Note that some frequently used kernels (such as the Sigmoid kernel)\n",
+ "don’t respect all of Mercer’s conditions, yet they generally work well\n",
+ "in practice.\n",
+ "\n",
+ "\n",
+ "## The moons example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from __future__ import division, print_function, unicode_literals\n",
+ "\n",
+ "import numpy as np\n",
+ "np.random.seed(42)\n",
+ "\n",
+ "import matplotlib\n",
+ "import matplotlib.pyplot as plt\n",
+ "plt.rcParams['axes.labelsize'] = 14\n",
+ "plt.rcParams['xtick.labelsize'] = 12\n",
+ "plt.rcParams['ytick.labelsize'] = 12\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn import datasets\n",
+ "\n",
+ "\n",
+ "\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "from sklearn.svm import LinearSVC\n",
+ "\n",
+ "\n",
+ "from sklearn.datasets import make_moons\n",
+ "X, y = make_moons(n_samples=100, noise=0.15, random_state=42)\n",
+ "\n",
+ "def plot_dataset(X, y, axes):\n",
+ " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"bs\")\n",
+ " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"g^\")\n",
+ " plt.axis(axes)\n",
+ " plt.grid(True, which='both')\n",
+ " plt.xlabel(r\"$x_1$\", fontsize=20)\n",
+ " plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n",
+ "\n",
+ "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n",
+ "plt.show()\n",
+ "\n",
+ "from sklearn.datasets import make_moons\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "\n",
+ "polynomial_svm_clf = Pipeline([\n",
+ " (\"poly_features\", PolynomialFeatures(degree=3)),\n",
+ " (\"scaler\", StandardScaler()),\n",
+ " (\"svm_clf\", LinearSVC(C=10, loss=\"hinge\", random_state=42))\n",
+ " ])\n",
+ "\n",
+ "polynomial_svm_clf.fit(X, y)\n",
+ "\n",
+ "def plot_predictions(clf, axes):\n",
+ " x0s = np.linspace(axes[0], axes[1], 100)\n",
+ " x1s = np.linspace(axes[2], axes[3], 100)\n",
+ " x0, x1 = np.meshgrid(x0s, x1s)\n",
+ " X = np.c_[x0.ravel(), x1.ravel()]\n",
+ " y_pred = clf.predict(X).reshape(x0.shape)\n",
+ " y_decision = clf.decision_function(X).reshape(x0.shape)\n",
+ " plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)\n",
+ " plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)\n",
+ "\n",
+ "plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])\n",
+ "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "\n",
+ "poly_kernel_svm_clf = Pipeline([\n",
+ " (\"scaler\", StandardScaler()),\n",
+ " (\"svm_clf\", SVC(kernel=\"poly\", degree=3, coef0=1, C=5))\n",
+ " ])\n",
+ "poly_kernel_svm_clf.fit(X, y)\n",
+ "\n",
+ "poly100_kernel_svm_clf = Pipeline([\n",
+ " (\"scaler\", StandardScaler()),\n",
+ " (\"svm_clf\", SVC(kernel=\"poly\", degree=10, coef0=100, C=5))\n",
+ " ])\n",
+ "poly100_kernel_svm_clf.fit(X, y)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n",
+ "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n",
+ "plt.title(r\"$d=3, r=1, C=5$\", fontsize=18)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n",
+ "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n",
+ "plt.title(r\"$d=10, r=100, C=5$\", fontsize=18)\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "def gaussian_rbf(x, landmark, gamma):\n",
+ " return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)\n",
+ "\n",
+ "gamma = 0.3\n",
+ "\n",
+ "x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)\n",
+ "x2s = gaussian_rbf(x1s, -2, gamma)\n",
+ "x3s = gaussian_rbf(x1s, 1, gamma)\n",
+ "\n",
+ "XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]\n",
+ "yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plt.grid(True, which='both')\n",
+ "plt.axhline(y=0, color='k')\n",
+ "plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c=\"red\")\n",
+ "plt.plot(X1D[:, 0][yk==0], np.zeros(4), \"bs\")\n",
+ "plt.plot(X1D[:, 0][yk==1], np.zeros(5), \"g^\")\n",
+ "plt.plot(x1s, x2s, \"g--\")\n",
+ "plt.plot(x1s, x3s, \"b:\")\n",
+ "plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])\n",
+ "plt.xlabel(r\"$x_1$\", fontsize=20)\n",
+ "plt.ylabel(r\"Similarity\", fontsize=14)\n",
+ "plt.annotate(r'$\\mathbf{x}$',\n",
+ " xy=(X1D[3, 0], 0),\n",
+ " xytext=(-0.5, 0.20),\n",
+ " ha=\"center\",\n",
+ " arrowprops=dict(facecolor='black', shrink=0.1),\n",
+ " fontsize=18,\n",
+ " )\n",
+ "plt.text(-2, 0.9, \"$x_2$\", ha=\"center\", fontsize=20)\n",
+ "plt.text(1, 0.9, \"$x_3$\", ha=\"center\", fontsize=20)\n",
+ "plt.axis([-4.5, 4.5, -0.1, 1.1])\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plt.grid(True, which='both')\n",
+ "plt.axhline(y=0, color='k')\n",
+ "plt.axvline(x=0, color='k')\n",
+ "plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], \"bs\")\n",
+ "plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], \"g^\")\n",
+ "plt.xlabel(r\"$x_2$\", fontsize=20)\n",
+ "plt.ylabel(r\"$x_3$ \", fontsize=20, rotation=0)\n",
+ "plt.annotate(r'$\\phi\\left(\\mathbf{x}\\right)$',\n",
+ " xy=(XK[3, 0], XK[3, 1]),\n",
+ " xytext=(0.65, 0.50),\n",
+ " ha=\"center\",\n",
+ " arrowprops=dict(facecolor='black', shrink=0.1),\n",
+ " fontsize=18,\n",
+ " )\n",
+ "plt.plot([-0.1, 1.1], [0.57, -0.1], \"r--\", linewidth=3)\n",
+ "plt.axis([-0.1, 1.1, -0.1, 1.1])\n",
+ " \n",
+ "plt.subplots_adjust(right=1)\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "x1_example = X1D[3, 0]\n",
+ "for landmark in (-2, 1):\n",
+ " k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)\n",
+ " print(\"Phi({}, {}) = {}\".format(x1_example, landmark, k))\n",
+ "\n",
+ "rbf_kernel_svm_clf = Pipeline([\n",
+ " (\"scaler\", StandardScaler()),\n",
+ " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=5, C=0.001))\n",
+ " ])\n",
+ "rbf_kernel_svm_clf.fit(X, y)\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "\n",
+ "gamma1, gamma2 = 0.1, 5\n",
+ "C1, C2 = 0.001, 1000\n",
+ "hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)\n",
+ "\n",
+ "svm_clfs = []\n",
+ "for gamma, C in hyperparams:\n",
+ " rbf_kernel_svm_clf = Pipeline([\n",
+ " (\"scaler\", StandardScaler()),\n",
+ " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=gamma, C=C))\n",
+ " ])\n",
+ " rbf_kernel_svm_clf.fit(X, y)\n",
+ " svm_clfs.append(rbf_kernel_svm_clf)\n",
+ "\n",
+ "plt.figure(figsize=(11, 7))\n",
+ "\n",
+ "for i, svm_clf in enumerate(svm_clfs):\n",
+ " plt.subplot(221 + i)\n",
+ " plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])\n",
+ " plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n",
+ " gamma, C = hyperparams[i]\n",
+ " plt.title(r\"$\\gamma = {}, C = {}$\".format(gamma, C), fontsize=16)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Mathematical optimization of convex functions\n",
+ "\n",
+ "A mathematical (quadratic) optimization problem, or just optimization problem, has the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n",
+ " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to some constraints for say a selected set $i=1,2,\\dots, n$.\n",
+ "In our case we are optimizing with respect to the Lagrangian multipliers $\\lambda_i$, and the\n",
+ "vector $\\boldsymbol{\\lambda}=[\\lambda_1, \\lambda_2,\\dots, \\lambda_n]$ is the optimization variable we are dealing with.\n",
+ "\n",
+ "In our case we are particularly interested in a class of optimization problems called convex optmization problems. \n",
+ "In our discussion on gradient descent methods we discussed at length the definition of a convex function. \n",
+ "\n",
+ "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/).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we use Python as programming language and wish to venture beyond\n",
+ "**scikit-learn**, **tensorflow** and similar software which makes our\n",
+ "lives so much easier, we need to dive into the wonderful world of\n",
+ "quadratic programming. We can, if we wish, solve the minimization\n",
+ "problem using say standard gradient methods or conjugate gradient\n",
+ "methods. However, these methods tend to exhibit a rather slow\n",
+ "converge. So, welcome to the promised land of quadratic programming.\n",
+ "\n",
+ "The functions we need are contained in the quadratic programming package **CVXOPT** and we need to import it together with **numpy** as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy\n",
+ "import cvxopt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This will make our life much easier. You don't need t write your own optimizer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We remind ourselves about the general problem we want to solve"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{P}\\boldsymbol{x}+\\boldsymbol{q}^T\\boldsymbol{x},\\\\ \\nonumber\n",
+ " &\\mathrm{subject\\hspace{0.1cm} to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{x} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{x}=f.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}x^2+5x+3y \\\\ \\nonumber\n",
+ " &\\mathrm{subject to} \\\\ \\nonumber\n",
+ " &x, y \\geq 0 \\\\ \\nonumber\n",
+ " &x+3y \\geq 15 \\\\ \\nonumber\n",
+ " &2x+5y \\leq 100 \\\\ \\nonumber\n",
+ " &3x+4y \\leq 80. \\\\ \\nonumber\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have collapsed all the inequalities into a single matrix $\\boldsymbol{G}$. We see also that our matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{P} =\\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is clearly positive semi-definite (all eigenvalues larger or equal zero). \n",
+ "Finally, the vector $\\boldsymbol{h}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{h} = \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since we don't have any equalities the matrix $\\boldsymbol{A}$ is set to zero\n",
+ "The following code solves the equations for us"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Import the necessary packages\n",
+ "import numpy\n",
+ "from cvxopt import matrix\n",
+ "from cvxopt import solvers\n",
+ "P = matrix(numpy.diag([1,0]), tc=’d’)\n",
+ "q = matrix(numpy.array([3,4]), tc=’d’)\n",
+ "G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)\n",
+ "h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)\n",
+ "# Construct the QP, invoke solver\n",
+ "sol = solvers.qp(P,q,G,h)\n",
+ "# Extract optimal value and solution\n",
+ "sol[’x’] \n",
+ "sol[’primal objective’]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n",
+ "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2K(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n",
+ "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{I}\\boldsymbol{\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n",
+ "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n",
+ "With the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n",
+ "\n",
+ "**code will be added**"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter6.ipynb b/doc/LectureNotes/_build/html/_sources/chapter6.ipynb
new file mode 100644
index 000000000..01884f54a
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter6.ipynb
@@ -0,0 +1,1301 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Decision trees, overarching aims\n",
+ "\n",
+ "\n",
+ "We start here with the most basic algorithm, the so-called decision\n",
+ "tree. With this basic algorithm we can in turn build more complex\n",
+ "networks, spanning from homogeneous and heterogenous forests (bagging,\n",
+ "random forests and more) to one of the most popular supervised\n",
+ "algorithms nowadays, the extreme gradient boosting, or just\n",
+ "XGBoost. But let us start with the simplest possible ingredient.\n",
+ "\n",
+ "Decision trees are supervised learning algorithms used for both,\n",
+ "classification and regression tasks.\n",
+ "\n",
+ "\n",
+ "The main idea of decision trees\n",
+ "is to find those descriptive features which contain the most\n",
+ "**information** regarding the target feature and then split the dataset\n",
+ "along the values of these features such that the target feature values\n",
+ "for the resulting underlying datasets are as pure as possible.\n",
+ "\n",
+ "The descriptive features which reproduce best the target/output features are normally said\n",
+ "to be the most informative ones. The process of finding the **most\n",
+ "informative** feature is done until we accomplish a stopping criteria\n",
+ "where we then finally end up in so called **leaf nodes**. \n",
+ "\n",
+ "## Basics of a tree\n",
+ "\n",
+ "A decision tree is typically divided into a **root node**, the **interior nodes**,\n",
+ "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n",
+ "\n",
+ "The leaf nodes\n",
+ "contain the predictions we will make for new query instances presented\n",
+ "to our trained model. This is possible since the model has \n",
+ "learned the underlying structure of the training data and hence can,\n",
+ "given some assumptions, make predictions about the target feature value\n",
+ "(class) of unseen query instances.\n",
+ "\n",
+ "\n",
+ "## General Features\n",
+ "\n",
+ "The overarching approach to decision trees is a top-down approach.\n",
+ "\n",
+ "* A leaf provides the classification of a given instance.\n",
+ "\n",
+ "* A node specifies a test of some attribute of the instance.\n",
+ "\n",
+ "* A branch corresponds to a possible values of an attribute.\n",
+ "\n",
+ "* 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.\n",
+ "\n",
+ "This process is then repeated for the subtree rooted at the new\n",
+ "node.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In simplified terms, the process of training a decision tree and\n",
+ "predicting the target features of query instances is as follows:\n",
+ "\n",
+ "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n",
+ "\n",
+ "2. 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\n",
+ "\n",
+ "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n",
+ "\n",
+ "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n",
+ "\n",
+ "Then we are essentially done!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "steps=250\n",
+ "\n",
+ "distance=0\n",
+ "x=0\n",
+ "distance_list=[]\n",
+ "steps_list=[]\n",
+ "while x\n",
+ "\n",
+ "
Day
Outlook
Temperature
Humidity
Wind
Ride
\n",
+ "\n",
+ "\n",
+ "
1
Sunny
Hot
High
Weak
0
\n",
+ "
2
Sunny
Hot
High
Strong
1
\n",
+ "
3
Overcast
Hot
High
Weak
1
\n",
+ "
4
Rain
Mild
High
Weak
1
\n",
+ "
5
Rain
Cool
Normal
Weak
1
\n",
+ "
6
Rain
Cool
Normal
Strong
0
\n",
+ "
7
Overcast
Cool
Normal
Strong
1
\n",
+ "
8
Sunny
Mild
High
Weak
0
\n",
+ "
9
Sunny
Cool
Normal
Weak
1
\n",
+ "
10
Rain
Mild
Normal
Weak
1
\n",
+ "
11
Sunny
Mild
Normal
Strong
1
\n",
+ "
12
Overcast
Mild
High
Strong
1
\n",
+ "
13
Overcast
Hot
Normal
Weak
1
\n",
+ "
14
Rain
Mild
High
Strong
0
\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Simple Python Code to read in Data and perform Classification"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.tree import export_graphviz\n",
+ "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
+ "from sklearn.compose import ColumnTransformer\n",
+ "from IPython.display import Image \n",
+ "from pydot import graph_from_dot_data\n",
+ "import os\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"rideclass.csv\"),'r')\n",
+ "\n",
+ "# Read the experimental data with Pandas\n",
+ "from IPython.display import display\n",
+ "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n",
+ "ridedata = pd.DataFrame(ridedata)\n",
+ "\n",
+ "# Features and targets\n",
+ "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n",
+ "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n",
+ "\n",
+ "# Create the encoder.\n",
+ "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n",
+ "# Assume for simplicity all features are categorical.\n",
+ "encoder.fit(X) \n",
+ "# Apply the encoder.\n",
+ "X = encoder.transform(X)\n",
+ "print(X)\n",
+ "# Then do a Classification tree\n",
+ "tree_clf = DecisionTreeClassifier(max_depth=2)\n",
+ "tree_clf.fit(X, y)\n",
+ "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n",
+ "#transfer to a decision tree graph\n",
+ "export_graphviz(\n",
+ " tree_clf,\n",
+ " out_file=\"DataFiles/ride.dot\",\n",
+ " rounded=True,\n",
+ " filled=True\n",
+ ")\n",
+ "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
+ "os.system(cmd)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The above functions (gini, entropy and misclassification error) are\n",
+ "important components of the so-called CART algorithm. We will discuss\n",
+ "this algorithm below after we have discussed the information gain\n",
+ "algorithm ID3.\n",
+ "\n",
+ "In the example here we have converted all our attributes into numerical values $0,1,2$ etc."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Split a dataset based on an attribute and an attribute value\n",
+ "def test_split(index, value, dataset):\n",
+ "\tleft, right = list(), list()\n",
+ "\tfor row in dataset:\n",
+ "\t\tif row[index] < value:\n",
+ "\t\t\tleft.append(row)\n",
+ "\t\telse:\n",
+ "\t\t\tright.append(row)\n",
+ "\treturn left, right\n",
+ " \n",
+ "# Calculate the Gini index for a split dataset\n",
+ "def gini_index(groups, classes):\n",
+ "\t# count all samples at split point\n",
+ "\tn_instances = float(sum([len(group) for group in groups]))\n",
+ "\t# sum weighted Gini index for each group\n",
+ "\tgini = 0.0\n",
+ "\tfor group in groups:\n",
+ "\t\tsize = float(len(group))\n",
+ "\t\t# avoid divide by zero\n",
+ "\t\tif size == 0:\n",
+ "\t\t\tcontinue\n",
+ "\t\tscore = 0.0\n",
+ "\t\t# score the group based on the score for each class\n",
+ "\t\tfor class_val in classes:\n",
+ "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n",
+ "\t\t\tscore += p * p\n",
+ "\t\t# weight the group score by its relative size\n",
+ "\t\tgini += (1.0 - score) * (size / n_instances)\n",
+ "\treturn gini\n",
+ "\n",
+ "# Select the best split point for a dataset\n",
+ "def get_split(dataset):\n",
+ "\tclass_values = list(set(row[-1] for row in dataset))\n",
+ "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n",
+ "\tfor index in range(len(dataset[0])-1):\n",
+ "\t\tfor row in dataset:\n",
+ "\t\t\tgroups = test_split(index, row[index], dataset)\n",
+ "\t\t\tgini = gini_index(groups, class_values)\n",
+ "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n",
+ "\t\t\tif gini < b_score:\n",
+ "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n",
+ "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n",
+ " \n",
+ "dataset = [[0,0,0,0,0],\n",
+ " [0,0,0,1,1],\n",
+ " [1,0,0,0,1],\n",
+ " [2,1,0,0,1],\n",
+ " [2,2,1,0,1],\n",
+ " [2,2,1,1,0],\n",
+ " [1,2,1,1,1],\n",
+ " [0,1,0,0,0],\n",
+ " [0,2,1,0,1],\n",
+ " [2,1,1,0,1],\n",
+ " [0,1,1,1,1],\n",
+ " [1,1,0,1,1],\n",
+ " [1,0,1,0,1],\n",
+ " [2,1,0,1,0]]\n",
+ "\n",
+ "split = get_split(dataset)\n",
+ "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Entropy and the ID3 algorithm\n",
+ "\n",
+ "The ID3 algorithm learns decision trees by constructing\n",
+ "them in a top down way, beginning with the question **which attribute should be tested at the root of the tree**?\n",
+ "\n",
+ "1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n",
+ "\n",
+ "2. The best attribute is selected and used as the test at the root node of the tree.\n",
+ "\n",
+ "3. A descendant of the root node is then created for each possible value of this attribute.\n",
+ "\n",
+ "4. Training examples are sorted to the appropriate descendant node.\n",
+ "\n",
+ "5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n",
+ "\n",
+ "6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n",
+ "\n",
+ "The ID3 algorithm selects which attribute to test at each node in the\n",
+ "tree.\n",
+ "\n",
+ "We would like to select the attribute that is most useful for classifying\n",
+ "examples.\n",
+ "\n",
+ "What is a good quantitative measure of the worth of an attribute?\n",
+ "\n",
+ "Information gain measures how well a given attribute separates the\n",
+ "training examples according to their target classification.\n",
+ "\n",
+ "The ID3 algorithm uses this information gain measure to select among the candidate\n",
+ "attributes at each step while growing the tree.\n",
+ "\n",
+ "\n",
+ "### Cancer Data again now with Decision Trees and other Methods"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "# Logistic Regression\n",
+ "logreg = LogisticRegression(solver='lbfgs')\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "# Support vector machine\n",
+ "svm = SVC(gamma='auto', C=100)\n",
+ "svm.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n",
+ "deep_tree_clf.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# Logistic Regression\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Support Vector Machine\n",
+ "svm.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Another example, the moons again"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from __future__ import division, print_function, unicode_literals\n",
+ "\n",
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import os\n",
+ "\n",
+ "# to make this notebook's output stable across runs\n",
+ "np.random.seed(42)\n",
+ "\n",
+ "# To plot pretty figures\n",
+ "import matplotlib\n",
+ "import matplotlib.pyplot as plt\n",
+ "from matplotlib.colors import ListedColormap\n",
+ "plt.rcParams['axes.labelsize'] = 14\n",
+ "plt.rcParams['xtick.labelsize'] = 12\n",
+ "plt.rcParams['ytick.labelsize'] = 12\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn import datasets\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "from sklearn.datasets import make_moons\n",
+ "from sklearn.tree import export_graphviz\n",
+ "\n",
+ "Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
+ "\n",
+ "deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n",
+ "deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n",
+ "deep_tree_clf1.fit(Xm, ym)\n",
+ "deep_tree_clf2.fit(Xm, ym)\n",
+ "\n",
+ "\n",
+ "def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n",
+ " x1s = np.linspace(axes[0], axes[1], 100)\n",
+ " x2s = np.linspace(axes[2], axes[3], 100)\n",
+ " x1, x2 = np.meshgrid(x1s, x2s)\n",
+ " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
+ " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
+ " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
+ " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
+ " if not iris:\n",
+ " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
+ " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
+ " if plot_training:\n",
+ " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n",
+ " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n",
+ " plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n",
+ " plt.axis(axes)\n",
+ " if iris:\n",
+ " plt.xlabel(\"Petal length\", fontsize=14)\n",
+ " plt.ylabel(\"Petal width\", fontsize=14)\n",
+ " else:\n",
+ " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
+ " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
+ " if legend:\n",
+ " plt.legend(loc=\"lower right\", fontsize=14)\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
+ "plt.title(\"No restrictions\", fontsize=16)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
+ "plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "np.random.seed(6)\n",
+ "Xs = np.random.rand(100, 2) - 0.5\n",
+ "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n",
+ "\n",
+ "angle = np.pi/4\n",
+ "rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n",
+ "Xsr = Xs.dot(rotation_matrix)\n",
+ "\n",
+ "tree_clf_s = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf_s.fit(Xs, ys)\n",
+ "tree_clf_sr = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf_sr.fit(Xsr, ys)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Quadratic training set + noise\n",
+ "np.random.seed(42)\n",
+ "m = 200\n",
+ "X = np.random.rand(m, 1)\n",
+ "y = 4 * (X - 0.5) ** 2\n",
+ "y = y + np.random.randn(m, 1) / 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n",
+ "tree_reg.fit(X, y)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n",
+ " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n",
+ " y_pred = tree_reg.predict(x1)\n",
+ " plt.axis(axes)\n",
+ " plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ " if ylabel:\n",
+ " plt.ylabel(ylabel, fontsize=18, rotation=0)\n",
+ " plt.plot(X, y, \"b.\")\n",
+ " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_regression_predictions(tree_reg1, X, y)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n",
+ "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n",
+ "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"max_depth=2\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n",
+ " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n",
+ "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n",
+ "plt.title(\"max_depth=3\", fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "tree_reg1 = DecisionTreeRegressor(random_state=42)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n",
+ "y_pred1 = tree_reg1.predict(x1)\n",
+ "y_pred2 = tree_reg2.predict(x1)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"No restrictions\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Pros and cons of trees, pros\n",
+ "\n",
+ "* 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)\n",
+ "\n",
+ "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n",
+ "\n",
+ "* No feature normalization needed\n",
+ "\n",
+ "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n",
+ "\n",
+ "* Can model nonlinear relationships\n",
+ "\n",
+ "* Can model interactions between the different descriptive features\n",
+ "\n",
+ "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n",
+ "\n",
+ "### Disadvantages\n",
+ "\n",
+ "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
+ "\n",
+ "* If continuous features are used the tree may become quite large and hence less interpretable\n",
+ "\n",
+ "* 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\n",
+ "\n",
+ "* 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\n",
+ "\n",
+ "* 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. \n",
+ "\n",
+ "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n",
+ "\n",
+ "* 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\n",
+ "\n",
+ "However, by aggregating many decision trees, using methods like\n",
+ "bagging, random forests, and boosting, the predictive performance of\n",
+ "trees can be substantially improved."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter7.ipynb b/doc/LectureNotes/_build/html/_sources/chapter7.ipynb
new file mode 100644
index 000000000..49dd8591c
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter7.ipynb
@@ -0,0 +1,1580 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n",
+ "\n",
+ "As stated previously and seen in many of the examples discussed in the previous chapter about\n",
+ "a single decision tree, we often end up overfitting our training\n",
+ "data. This normally means that we have a high variance. Can we reduce\n",
+ "the variance of a statistical learning method?\n",
+ "\n",
+ "This leads us to a set of different methods that can combine different\n",
+ "machine learning algorithms or just use one of them to construct\n",
+ "forests and jungles of trees, homogeneous ones or heterogenous\n",
+ "ones. These methods are recognized by different names which we will\n",
+ "try to explain here. These are\n",
+ "\n",
+ "1. Voting classifiers\n",
+ "\n",
+ "2. Bagging and Pasting\n",
+ "\n",
+ "3. Random forests\n",
+ "\n",
+ "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n",
+ "\n",
+ "We discuss these methods here.\n",
+ "\n",
+ "### An Overview of Ensemble Methods\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Bagging\n",
+ "\n",
+ "The **plain** decision trees suffer from high\n",
+ "variance. This means that if we split the training data into two parts\n",
+ "at random, and fit a decision tree to both halves, the results that we\n",
+ "get could be quite different. In contrast, a procedure with low\n",
+ "variance will yield similar results if applied repeatedly to distinct\n",
+ "data sets; linear regression tends to have low variance, if the ratio\n",
+ "of $n$ to $p$ is moderately large. \n",
+ "\n",
+ "**Bootstrap aggregation**, or just **bagging**, is a\n",
+ "general-purpose procedure for reducing the variance of a statistical\n",
+ "learning method. \n",
+ "\n",
+ "\n",
+ "Bagging typically results in improved accuracy\n",
+ "over prediction using a single tree. Unfortunately, however, it can be\n",
+ "difficult to interpret the resulting model. Recall that one of the\n",
+ "advantages of decision trees is the attractive and easily interpreted\n",
+ "diagram that results.\n",
+ "\n",
+ "However, when we bag a large number of trees, it is no longer\n",
+ "possible to represent the resulting statistical learning procedure\n",
+ "using a single tree, and it is no longer clear which variables are\n",
+ "most important to the procedure. Thus, bagging improves prediction\n",
+ "accuracy at the expense of interpretability. Although the collection\n",
+ "of bagged trees is much more difficult to interpret than a single\n",
+ "tree, one can obtain an overall summary of the importance of each\n",
+ "predictor using the MSE (for bagging regression trees) or the Gini\n",
+ "index (for bagging classification trees). In the case of bagging\n",
+ "regression trees, we can record the total amount that the MSE is\n",
+ "decreased due to splits over a given predictor, averaged over all $B$ possible\n",
+ "trees. A large value indicates an important predictor. Similarly, in\n",
+ "the context of bagging classification trees, we can add up the total\n",
+ "amount that the Gini index is decreased by splits over a given\n",
+ "predictor, averaged over all $B$ trees."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "heads_proba = 0.51\n",
+ "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n",
+ "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n",
+ "plt.figure(figsize=(8,3.5))\n",
+ "plt.plot(cumulative_heads_ratio)\n",
+ "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n",
+ "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n",
+ "plt.xlabel(\"Number of coin tosses\")\n",
+ "plt.ylabel(\"Heads ratio\")\n",
+ "plt.legend(loc=\"lower right\")\n",
+ "plt.axis([0, 10000, 0.42, 0.58])\n",
+ "save_fig(\"votingsimple\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.datasets import make_moons\n",
+ "\n",
+ "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
+ "\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "from sklearn.ensemble import VotingClassifier\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.svm import SVC\n",
+ "\n",
+ "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
+ "svm_clf = SVC(gamma=\"auto\", random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='hard')\n",
+ "\n",
+ "voting_clf.fit(X_train, y_train)\n",
+ "\n",
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n",
+ "\n",
+ "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
+ "svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='soft')\n",
+ "voting_clf.fit(X_train, y_train)\n",
+ "\n",
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.datasets import make_moons\n",
+ "\n",
+ "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "from sklearn.ensemble import VotingClassifier\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.svm import SVC\n",
+ "\n",
+ "log_clf = LogisticRegression(random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(random_state=42)\n",
+ "svm_clf = SVC(random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='hard')\n",
+ "voting_clf.fit(X_train, y_train)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "log_clf = LogisticRegression(random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(random_state=42)\n",
+ "svm_clf = SVC(probability=True, random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='soft')\n",
+ "voting_clf.fit(X_train, y_train)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Bagging Examples"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.ensemble import BaggingClassifier\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "\n",
+ "bag_clf = BaggingClassifier(\n",
+ " DecisionTreeClassifier(random_state=42), n_estimators=500,\n",
+ " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n",
+ "bag_clf.fit(X_train, y_train)\n",
+ "y_pred = bag_clf.predict(X_test)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "print(accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "tree_clf = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf.fit(X_train, y_train)\n",
+ "y_pred_tree = tree_clf.predict(X_test)\n",
+ "print(accuracy_score(y_test, y_pred_tree))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "from matplotlib.colors import ListedColormap\n",
+ "\n",
+ "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n",
+ " x1s = np.linspace(axes[0], axes[1], 100)\n",
+ " x2s = np.linspace(axes[2], axes[3], 100)\n",
+ " x1, x2 = np.meshgrid(x1s, x2s)\n",
+ " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
+ " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
+ " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
+ " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
+ " if contour:\n",
+ " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
+ " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
+ " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n",
+ " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n",
+ " plt.axis(axes)\n",
+ " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
+ " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
+ "plt.figure(figsize=(11,4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(tree_clf, X, y)\n",
+ "plt.title(\"Decision Tree\", fontsize=14)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(bag_clf, X, y)\n",
+ "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n",
+ "save_fig(\"baggingtree\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Making your own Bootstrap: Changing the Level of the Decision Tree\n",
+ "\n",
+ "Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n",
+ "a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "n = 100\n",
+ "n_boostraps = 100\n",
+ "maxdepth = 8\n",
+ "\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",
+ "error = np.zeros(maxdepth)\n",
+ "bias = np.zeros(maxdepth)\n",
+ "variance = np.zeros(maxdepth)\n",
+ "polydegree = np.zeros(maxdepth)\n",
+ "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# we produce a simple tree first as benchmark\n",
+ "simpletree = DecisionTreeRegressor(max_depth=3) \n",
+ "simpletree.fit(X_train_scaled, y_train)\n",
+ "simpleprediction = simpletree.predict(X_test_scaled)\n",
+ "for degree in range(1,maxdepth):\n",
+ " model = DecisionTreeRegressor(max_depth=degree) \n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(X_train_scaled, y_train)\n",
+ " model.fit(x_, y_)\n",
+ " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ " \n",
+ "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)\n",
+ "print(mse_simpletree)\n",
+ "plt.xlim(1,maxdepth)\n",
+ "plt.plot(polydegree, error, label='MSE')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "save_fig(\"baggingboot\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Random forests\n",
+ "\n",
+ "Random forests provide an improvement over bagged trees by way of a\n",
+ "small tweak that decorrelates the trees. \n",
+ "\n",
+ "As in bagging, we build a\n",
+ "number of decision trees on bootstrapped training samples. But when\n",
+ "building these decision trees, each time a split in a tree is\n",
+ "considered, a random sample of $m$ predictors is chosen as split\n",
+ "candidates from the full set of $p$ predictors. The split is allowed to\n",
+ "use only one of those $m$ predictors. \n",
+ "\n",
+ "A fresh sample of $m$ predictors is\n",
+ "taken at each split, and typically we choose"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "m\\approx \\sqrt{p}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In building a random forest, at\n",
+ "each split in the tree, the algorithm is not even allowed to consider\n",
+ "a majority of the available predictors. \n",
+ "\n",
+ "The reason for this is rather clever. Suppose that there is one very\n",
+ "strong predictor in the data set, along with a number of other\n",
+ "moderately strong predictors. Then in the collection of bagged\n",
+ "variable importance random forest trees, most or all of the trees will\n",
+ "use this strong predictor in the top split. Consequently, all of the\n",
+ "bagged trees will look quite similar to each other. Hence the\n",
+ "predictions from the bagged trees will be highly correlated.\n",
+ "Unfortunately, averaging many highly correlated quantities does not\n",
+ "lead to as large of a reduction in variance as averaging many\n",
+ "uncorrelated quantities. In particular, this means that bagging will\n",
+ "not lead to a substantial reduction in variance over a single tree in\n",
+ "this setting.\n",
+ "\n",
+ "\n",
+ "The algorithm described here can be applied to both classification and regression problems.\n",
+ "\n",
+ "We will grow of forest of say $B$ trees.\n",
+ "1. For $b=1:B$\n",
+ "\n",
+ " * Draw a bootstrap sample from the training data organized in our $\\boldsymbol{X}$ matrix.\n",
+ "\n",
+ " * 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\n",
+ "\n",
+ "1. we select $m \\le p$ variables at random from the $p$ predictors/features\n",
+ "\n",
+ "2. pick the best split point among the $m$ features using for example the CART algorithm and create a new node\n",
+ "\n",
+ "3. split the node into daughter nodes\n",
+ "\n",
+ "\n",
+ "\n",
+ "4. 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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "from sklearn.ensemble import BaggingClassifier\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "# Logistic Regression\n",
+ "logreg = LogisticRegression(solver='lbfgs')\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "# Support vector machine\n",
+ "svm = SVC(gamma='auto', C=100)\n",
+ "svm.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n",
+ "deep_tree_clf.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# Logistic Regression\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Support Vector Machine\n",
+ "svm.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "from sklearn.preprocessing import LabelEncoder\n",
+ "from sklearn.model_selection import cross_validate\n",
+ "# Data set not specificied\n",
+ "#Instantiate the model with 500 trees and entropy as splitting criteria\n",
+ "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n",
+ "Random_Forest_model.fit(X_train_scaled, y_train)\n",
+ "#Cross validation\n",
+ "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n",
+ "print(accuracy)\n",
+ "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "\n",
+ "import scikitplot as skplt\n",
+ "y_pred = Random_Forest_model.predict(X_test_scaled)\n",
+ "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
+ "plt.show()\n",
+ "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n",
+ "skplt.metrics.plot_roc(y_test, y_probas)\n",
+ "plt.show()\n",
+ "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Recall that the cumulative gains curve shows the percentage of the\n",
+ "overall number of cases in a given category *gained* by targeting a\n",
+ "percentage of the total number of cases.\n",
+ "\n",
+ "Similarly, the receiver operating characteristic curve, or ROC curve,\n",
+ "displays the diagnostic ability of a binary classifier system as its\n",
+ "discrimination threshold is varied. It plots the true positive rate against the false positive rate.\n",
+ "\n",
+ "\n",
+ "### Compare Bagging on Trees with Random Forests"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "bag_clf = BaggingClassifier(\n",
+ " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n",
+ " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "bag_clf.fit(X_train, y_train)\n",
+ "y_pred = bag_clf.predict(X_test)\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n",
+ "rnd_clf.fit(X_train, y_train)\n",
+ "y_pred_rf = rnd_clf.predict(X_test)\n",
+ "np.sum(y_pred == y_pred_rf) / len(y_pred)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Boosting, a Bird's Eye View\n",
+ "\n",
+ "The basic idea is to combine weak classifiers in order to create a good\n",
+ "classifier. With a weak classifier we often intend a classifier which\n",
+ "produces results which are only slightly better than we would get by\n",
+ "random guesses.\n",
+ "\n",
+ "This is done by applying in an iterative way a weak (or a standard\n",
+ "classifier like decision trees) to modify the data. In each iteration\n",
+ "we emphasize those observations which are misclassified by weighting\n",
+ "them with a factor.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Boosting is a way of fitting an additive expansion in a set of\n",
+ "elementary basis functions like for example some simple polynomials.\n",
+ "Assume for example that we have a function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\beta_m$ are the expansion parameters to be determined in a\n",
+ "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n",
+ "the multivariable parameter $x$ which is characterized by the\n",
+ "parameters $\\gamma_m$.\n",
+ "\n",
+ "As an example, consider the Sigmoid function we used in logistic\n",
+ "regression. In that case, we can translate the function\n",
+ "$b(x;\\gamma_m)$ into the Sigmoid function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n",
+ "$\\gamma_1$ were determined by the Logistic Regression fitting\n",
+ "algorithm.\n",
+ "\n",
+ "As another example, consider the cost function we defined for linear regression"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the function $f(x)$ was replaced by the design matrix\n",
+ "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n",
+ "that is $\\boldsymbol{f}=\\boldsymbol{X}\\boldsymbol{\\beta}$. In linear regression we can \n",
+ "simply invert a matrix and obtain the parameters $\\beta$ by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$.\n",
+ "\n",
+ "\n",
+ "### Iterative Fitting, Regression and Squared-error Cost Function\n",
+ "\n",
+ "The way we proceed is as follows (here we specialize to the squared-error cost function)\n",
+ "\n",
+ "1. Establish a cost function, here $\\cal{C}(\\boldsymbol{y},\\boldsymbol{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)$.\n",
+ "\n",
+ "2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.\n",
+ "\n",
+ "3. For $m=1:M$\n",
+ "\n",
+ "a. minimize $\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2$ wrt $\\gamma$ and $\\beta$\n",
+ "\n",
+ "b. This gives the optimal values $\\beta_m$ and $\\gamma_m$\n",
+ "\n",
+ "c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n",
+ "\n",
+ "\n",
+ "We could use any of the algorithms we have discussed till now. If we\n",
+ "use trees, $\\gamma$ parameterizes the split variables and split points\n",
+ "at the internal nodes, and the predictions at the terminal nodes.\n",
+ "\n",
+ "\n",
+ "\n",
+ "To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n",
+ "\n",
+ "For simplicity we assume also that our functions $b(x;\\gamma)=1+\\gamma x$. \n",
+ "\n",
+ "This means that for every iteration $m$, we need to optimize"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\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.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We start our iteration by simply setting $f_0(x)=0$. \n",
+ "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\cal{C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n",
+ "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n",
+ "\n",
+ "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\n",
+ "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "### Iterative Fitting, Classification and AdaBoost\n",
+ "\n",
+ "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\n",
+ "observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values \n",
+ "$\\{-1,1\\}$.\n",
+ "\n",
+ "The error rate of the training sample is then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The iterative procedure starts with defining a weak classifier whose\n",
+ "error rate is barely better than random guessing. The iterative\n",
+ "procedure in boosting is to sequentially apply a weak\n",
+ "classification algorithm to repeatedly modified versions of the data\n",
+ "producing a sequence of weak classifiers $G_m(x)$.\n",
+ "\n",
+ "Here we will express our function $f(x)$ in terms of $G(x)$. That is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "will be a function of"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In our iterative procedure we define thus"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n",
+ "exponential cost/loss function defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n",
+ "This is normally done in two steps. Let us however first rewrite the cost function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "First, for any $\\beta > 0$, we optimize $G$ by setting"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is the classifier that minimizes the weighted error rate in predicting $y$.\n",
+ "\n",
+ "We can do this by rewriting"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can be rewritten as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have redefined the error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to an update of"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This leads to the new weights"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Adaptive boosting: AdaBoost, Basic Algorithm\n",
+ "\n",
+ "The algorithm here is rather straightforward. Assume that our weak\n",
+ "classifier is a decision tree and we consider a binary set of outputs\n",
+ "with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n",
+ "observations. Our design matrix is given in terms of the\n",
+ "feature/predictor vectors\n",
+ "$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}]$. Finally, we define also a\n",
+ "classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\\boldsymbol{y}$. \n",
+ "\n",
+ "We have already defined the misclassification error $\\mathrm{err}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the function $I()$ is one if we misclassify and zero if we classify correctly. \n",
+ "\n",
+ "\n",
+ "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n",
+ "The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n",
+ "1. 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$.\n",
+ "\n",
+ "2. We rewrite the misclassification error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "1. 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.\n",
+ "\n",
+ "a. Fit then a given classifier to the training set using the weights $w_i$.\n",
+ "\n",
+ "b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n",
+ "\n",
+ "c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{\\overline{err}}_m)/\\mathrm{\\overline{err}}_m}$\n",
+ "\n",
+ "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n",
+ "\n",
+ "\n",
+ "5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n",
+ "\n",
+ "For the iterations with $m \\le 2$ the weights are modified\n",
+ "individually at each steps. The observations which were misclassified\n",
+ "at iteration $m-1$ have a weight which is larger than those which were\n",
+ "classified properly. As this proceeds, the observations which were\n",
+ "difficult to classifiy correctly are given a larger influence. Each\n",
+ "new classification step $m$ is then forced to concentrate on those\n",
+ "observations that are missed in the previous iterations.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.ensemble import AdaBoostClassifier\n",
+ "\n",
+ "ada_clf = AdaBoostClassifier(\n",
+ " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n",
+ " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n",
+ "ada_clf.fit(X_train, y_train)\n",
+ "\n",
+ "from sklearn.ensemble import AdaBoostClassifier\n",
+ "\n",
+ "ada_clf = AdaBoostClassifier(\n",
+ " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n",
+ " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n",
+ "ada_clf.fit(X_train_scaled, y_train)\n",
+ "y_pred = ada_clf.predict(X_test_scaled)\n",
+ "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
+ "plt.show()\n",
+ "y_probas = ada_clf.predict_proba(X_test_scaled)\n",
+ "skplt.metrics.plot_roc(y_test, y_probas)\n",
+ "plt.show()\n",
+ "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n",
+ "\n",
+ "Gradient boosting is again a similar technique to Adaptive boosting,\n",
+ "it combines so-called weak classifiers or regressors into a strong\n",
+ "method via a series of iterations.\n",
+ "\n",
+ "In order to understand the method, let us illustrate its basics by\n",
+ "bringing back the essential steps in linear regression, where our cost\n",
+ "function was the least squares function.\n",
+ "\n",
+ "\n",
+ "We start again with our cost function $\\cal{C}(\\boldsymbol{y}m\\boldsymbol{f})=\\sum_{i=0}^{n-1}\\cal{L}(y_i, f(x_i))$ where we want to minimize\n",
+ "This means that for every iteration, we need to optimize"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_M(x) = \\sum_{m=0}^M h_m(x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "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)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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\n",
+ "the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Optimizing with respect to $\\rho$ we obtain (taking the derivative) that $\\rho_1 = -1/2$. We have then that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can then proceed and compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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**. \n",
+ "\n",
+ "\n",
+ "Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,\n",
+ "so we do not learn a function that can generalize. However, we can modify the algorithm by\n",
+ "fitting a weak learner to approximate the negative gradient signal. \n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The way we proceed in an iterative fashion is to\n",
+ "1. Initialize our estimate $f_0(x)$.\n",
+ "\n",
+ "2. For $m=1:M$, we\n",
+ "\n",
+ "a. compute the negative gradient vector $\\boldsymbol{u}_m = -\\partial C(\\boldsymbol{y},\\boldsymbol{f})/\\partial \\boldsymbol{f}(x)$ at $f(x) = f_{m-1}(x)$;\n",
+ "\n",
+ "b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;\n",
+ "\n",
+ "c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;\n",
+ "\n",
+ "\n",
+ "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$.\n",
+ "\n",
+ "## Gradient Boosting, Examples of Regression"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.ensemble import GradientBoostingRegressor\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import scikitplot as skplt\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "\n",
+ "n = 100\n",
+ "maxdegree = 6\n",
+ "\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",
+ "\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = 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(1,maxdegree):\n",
+ " model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) \n",
+ " model.fit(X_train_scaled,y_train)\n",
+ " y_pred = model.predict(X_test_scaled)\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred) )\n",
+ " print('Max depth:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.xlim(1,maxdegree-1)\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "save_fig(\"gdregression\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Gradient Boosting, Classification Example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "import scikitplot as skplt\n",
+ "from sklearn.ensemble import GradientBoostingClassifier\n",
+ "from sklearn.model_selection import cross_validate\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0) \n",
+ "gd_clf.fit(X_train_scaled, y_train)\n",
+ "#Cross validation\n",
+ "accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']\n",
+ "print(accuracy)\n",
+ "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(gd_clf.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "import scikitplot as skplt\n",
+ "y_pred = gd_clf.predict(X_test_scaled)\n",
+ "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
+ "save_fig(\"gdclassiffierconfusion\")\n",
+ "plt.show()\n",
+ "y_probas = gd_clf.predict_proba(X_test_scaled)\n",
+ "skplt.metrics.plot_roc(y_test, y_probas)\n",
+ "save_fig(\"gdclassiffierroc\")\n",
+ "plt.show()\n",
+ "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
+ "save_fig(\"gdclassiffiercgain\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## XGBoost: Extreme Gradient Boosting\n",
+ "\n",
+ "\n",
+ "[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n",
+ "Boosting, is an optimized distributed gradient boosting library\n",
+ "designed to be highly efficient, flexible and portable. It implements\n",
+ "machine learning algorithms under the Gradient Boosting\n",
+ "framework. XGBoost provides a parallel tree boosting that solve many\n",
+ "data science problems in a fast and accurate way. See the [article by Chen and Guestrin](https://arxiv.org/abs/1603.02754).\n",
+ "\n",
+ "The authors design and build a highly scalable end-to-end tree\n",
+ "boosting system. It has a theoretically justified weighted quantile\n",
+ "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.\n",
+ "\n",
+ "It is now the algorithm which wins essentially all ML competitions!!!\n",
+ "\n",
+ "## Regression Case"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "import xgboost as xgb\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "import scikitplot as skplt\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "\n",
+ "n = 100\n",
+ "maxdegree = 6\n",
+ "\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",
+ "\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = 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 = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)\n",
+ "\n",
+ " model.fit(X_train_scaled,y_train)\n",
+ " y_pred = model.predict(X_test_scaled)\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred) )\n",
+ " print('Max depth:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.xlim(1,maxdegree-1)\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.preprocessing import LabelEncoder\n",
+ "from sklearn.model_selection import cross_validate\n",
+ "import scikitplot as skplt\n",
+ "import xgboost as xgb\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "xg_clf = xgb.XGBClassifier()\n",
+ "xg_clf.fit(X_train_scaled,y_train)\n",
+ "\n",
+ "y_test = xg_clf.predict(X_test_scaled)\n",
+ "\n",
+ "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(xg_clf.score(X_test_scaled,y_test)))\n",
+ "\n",
+ "import scikitplot as skplt\n",
+ "y_pred = xg_clf.predict(X_test_scaled)\n",
+ "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
+ "save_fig(\"xdclassiffierconfusion\")\n",
+ "plt.show()\n",
+ "y_probas = xg_clf.predict_proba(X_test_scaled)\n",
+ "skplt.metrics.plot_roc(y_test, y_probas)\n",
+ "save_fig(\"xdclassiffierroc\")\n",
+ "plt.show()\n",
+ "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
+ "save_fig(\"gdclassiffiercgain\")\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "xgb.plot_tree(xg_clf,num_trees=0)\n",
+ "plt.rcParams['figure.figsize'] = [50, 10]\n",
+ "save_fig(\"xgtree\")\n",
+ "plt.show()\n",
+ "\n",
+ "xgb.plot_importance(xg_clf)\n",
+ "plt.rcParams['figure.figsize'] = [5, 5]\n",
+ "save_fig(\"xgparams\")\n",
+ "plt.show()"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter8.ipynb b/doc/LectureNotes/_build/html/_sources/chapter8.ipynb
new file mode 100644
index 000000000..1ee4dd6cd
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter8.ipynb
@@ -0,0 +1,1359 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Basic ideas of the Principal Component Analysis (PCA)\n",
+ "\n",
+ "The principal component analysis deals with the problem of fitting a\n",
+ "low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n",
+ "the total dimension $D$ of the problem at hand (our data\n",
+ "set). Mathematically it can be formulated as a statistical problem or\n",
+ "a geometric problem. In our discussion of the theorem for the\n",
+ "classical PCA, we will stay with a statistical approach. \n",
+ "Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.\n",
+ "\n",
+ "We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n",
+ "* Each data point is determined by $p$ extrinsic (measurement) variables\n",
+ "\n",
+ "* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n",
+ "\n",
+ "* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n",
+ "\n",
+ "A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102).\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Introducing the Covariance and Correlation functions\n",
+ "\n",
+ "Before we discuss the PCA theorem, we need to remind ourselves about\n",
+ "the definition of the covariance and the correlation function. These are quantities \n",
+ "\n",
+ "Suppose we have defined two vectors\n",
+ "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With this definition and recalling that the variance is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite the covariance matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The covariance takes values between zero and infinity and may thus\n",
+ "lead to problems with loss of numerical precision for particularly\n",
+ "large values. It is common to scale the covariance matrix by\n",
+ "introducing instead the correlation matrix defined via the so-called\n",
+ "correlation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
+ "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
+ "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
+ "and $\\boldsymbol{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example this is the function we constructed using **pandas**.\n",
+ "\n",
+ "\n",
+ "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
+ "we defined the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
+ "entries $n$ being the row elements.\n",
+ "We can rewrite the design/feature matrix in terms of its column vectors as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a given vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions, we can now rewrite our $2\\times 2$\n",
+ "correaltion/covariance matrix in terms of a moe general design/feature\n",
+ "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
+ "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Numpy function **np.cov** calculates the covariance elements using\n",
+ "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
+ "the exact mean values. The following simple function uses the\n",
+ "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
+ "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
+ " x_1 & y_1 \\\\\n",
+ " x_2 & y_2\\\\\n",
+ " \\dots & \\dots \\\\\n",
+ " x_{n-2} & y_{n-2}\\\\\n",
+ " x_{n-1} & y_{n-1} & \n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
+ "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
+ "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "W = np.vstack((x, y))\n",
+ "C = np.cov(W)\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Correlation Matrix\n",
+ "\n",
+ "The previous example can be converted into the correlation matrix by\n",
+ "simply scaling the matrix elements with the variances. We should also\n",
+ "subtract the mean values for each column. This leads to the following\n",
+ "code which sets up the correlations matrix for the previous example in\n",
+ "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)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 100\n",
+ "# define two vectors \n",
+ "x = np.random.random(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "#scaling the x and y vectors \n",
+ "x = x - np.mean(x)\n",
+ "y = y - np.mean(y)\n",
+ "variance_x = np.sum(x@x)/n\n",
+ "variance_y = np.sum(y@y)/n\n",
+ "print(variance_x)\n",
+ "print(variance_y)\n",
+ "cov_xy = np.sum(x@y)/n\n",
+ "cov_xx = np.sum(x@x)/n\n",
+ "cov_yy = np.sum(y@y)/n\n",
+ "C = np.zeros((2,2))\n",
+ "C[0,0]= cov_xx/variance_x\n",
+ "C[1,1]= cov_yy/variance_y\n",
+ "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
+ "C[1,0]= C[0,1]\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that the matrix elements along the diagonal are one as they\n",
+ "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
+ "this matrix we easily see that it is a positive definite matrix.\n",
+ "\n",
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
+ "\n",
+ "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "x = x - np.mean(x)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "y = y - np.mean(y)\n",
+ "X = (np.vstack((x, y))).T\n",
+ "print(X)\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "print(Xpd)\n",
+ "correlation_matrix = Xpd.corr()\n",
+ "print(correlation_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We expand this model to the Franke function discussed above."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ "\treturn term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "def create_X(x, y, n ):\n",
+ "\tif len(x.shape) > 1:\n",
+ "\t\tx = np.ravel(x)\n",
+ "\t\ty = np.ravel(y)\n",
+ "\n",
+ "\tN = len(x)\n",
+ "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
+ "\tX = np.ones((N,l))\n",
+ "\n",
+ "\tfor i in range(1,n+1):\n",
+ "\t\tq = int((i)*(i+1)/2)\n",
+ "\t\tfor k in range(i+1):\n",
+ "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "\n",
+ "\treturn X\n",
+ "\n",
+ "\n",
+ "# Making meshgrid of datapoints and compute Franke's function\n",
+ "n = 4\n",
+ "N = 100\n",
+ "x = np.sort(np.random.uniform(0, 1, N))\n",
+ "y = np.sort(np.random.uniform(0, 1, N))\n",
+ "z = FrankeFunction(x, y)\n",
+ "X = create_X(x, y, n=n) \n",
+ "\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "# subtract the mean values and set up the covariance matrix\n",
+ "Xpd = Xpd - Xpd.mean()\n",
+ "covariance_matrix = Xpd.cov()\n",
+ "print(covariance_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note here that the covariance is zero for the first rows and\n",
+ "columns since all matrix elements in the design matrix were set to one\n",
+ "(we are fitting the function in terms of a polynomial of degree $n$). We would however not include the intercept\n",
+ "and wee can simply\n",
+ "drop these elements and construct a correlation\n",
+ "matrix without them. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00} & x_{01}\\\\\n",
+ "x_{10} & x_{11}\\\\\n",
+ "\\end{bmatrix}=\\begin{bmatrix}\n",
+ "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then compute the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
+ "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "\n",
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Towards the PCA theorem\n",
+ "\n",
+ "We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n",
+ "These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n",
+ "\n",
+ "Assume also that there is a transformation $\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n",
+ "\n",
+ "That is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}^T\\boldsymbol{X}^T\\boldsymbol{X}T\\boldsymbol{S}]=\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}$ from the left we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n",
+ "$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n",
+ "\n",
+ "\n",
+ "The eigenvalues tell us then how much we need to stretch the\n",
+ "corresponding eigenvectors. Dimensions with large eigenvalues have\n",
+ "thus large variations (large variance) and define therefore useful\n",
+ "dimensions. The data points are more spread out in the direction of\n",
+ "these eigenvectors. Smaller eigenvalues mean on the other hand that\n",
+ "the corresponding eigenvectors are shrunk accordingly and the data\n",
+ "points are tightly bunched together and there is not much variation in\n",
+ "these specific directions. Hopefully then we could leave it out\n",
+ "dimensions where the eigenvalues are very small. If $p$ is very large,\n",
+ "we could then aim at reducing $p$ to $l << p$ and handle only $l$\n",
+ "features/predictors.\n",
+ "\n",
+ "### The Algorithm before theorem\n",
+ "\n",
+ "Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. \n",
+ "* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Center the data by subtracting the mean value for each column. This leads to a new matrix $\\boldsymbol{X}\\rightarrow \\overline{\\boldsymbol{X}}$.\n",
+ "\n",
+ "* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}^T\\overline{\\boldsymbol{X}}]$.\n",
+ "\n",
+ "* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n",
+ "\n",
+ "* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n",
+ "\n",
+ "* 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.\n",
+ "\n",
+ "### Writing our own PCA code\n",
+ "\n",
+ "We will use a simple example first with two-dimensional data\n",
+ "drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n",
+ "2 & 2\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that the mean refers to each column of data. \n",
+ "We will generate $n = 10000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n",
+ "this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$. This is our design matrix where we have forced the covariance and mean values to take specific values.\n",
+ "\n",
+ "The following Python code aids in setting up the data and writing out the design matrix.\n",
+ "Note that the function **multivariate** returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from IPython.display import display\n",
+ "n = 10000\n",
+ "mean = (-1, 2)\n",
+ "cov = [[4, 2], [2, 2]]\n",
+ "X = np.random.multivariate_normal(mean, cov, n)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we are going to implement the PCA algorithm. We will break it down into various substeps.\n",
+ "\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\bar{x}_i = x_i - \\mu_n.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When you are done with these steps, print out $\\mu_n$ to verify it is\n",
+ "close to $\\mu$ and plot your mean centered data to verify it is\n",
+ "centered at the origin! \n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "df = pd.DataFrame(X)\n",
+ "# Pandas does the centering for us\n",
+ "df = df -df.mean()\n",
+ "# we center it ourselves\n",
+ "X_centered = X - X.mean(axis=0)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Alternatively, we could use the functions we discussed\n",
+ "earlier for scaling the data set. That is, we could have used the\n",
+ "**StandardScaler** function in **Scikit-Learn**, a function which ensures\n",
+ "that for each feature/predictor we study the mean value is zero and\n",
+ "the variance is one (every column in the design/feature matrix). You\n",
+ "would then not get the same results, since we divide by the\n",
+ "variance. The diagonal covariance matrix elements will then be one,\n",
+ "while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n",
+ "specific case.\n",
+ "\n",
+ "\n",
+ "Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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$.\n",
+ "We can write our own code or simply use either the functionaly of **numpy** or that of **pandas**, as follows"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "print(df.cov())\n",
+ "print(np.cov(X_centered.T))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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**. \n",
+ "Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\\times 2$ covariance matrix."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# extract the relevant columns from the centered design matrix of dim n x 2\n",
+ "x = X_centered[:,0]\n",
+ "y = X_centered[:,1]\n",
+ "Cov = np.zeros((2,2))\n",
+ "Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n",
+ "Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n",
+ "Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n",
+ "Cov[1,0]= Cov[0,1]\n",
+ "print(\"Centered covariance using own code\")\n",
+ "print(Cov)\n",
+ "plt.plot(x, y, 'x')\n",
+ "plt.axis('equal')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n",
+ "The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed. \n",
+ "\n",
+ "### Diagonalize the sample covariance matrix to obtain the principal components\n",
+ "\n",
+ "Now we are ready to solve for the principal components! To do so we\n",
+ "diagonalize the sample covariance matrix $\\Sigma$. We can use the\n",
+ "function **np.linalg.eig** to do so. It will return the eigenvalues and\n",
+ "eigenvectors of $\\Sigma$. Once we have these we can perform the \n",
+ "following tasks:\n",
+ "\n",
+ "* We compute the percentage of the total variance captured by the first principal component\n",
+ "\n",
+ "* We plot the mean centered data and lines along the first and second principal components\n",
+ "\n",
+ "* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n",
+ "\n",
+ "* Finally, we approximate the data as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $v_0$ is the first principal component. \n",
+ "\n",
+ "Collecting all these steps we can write our own PCA function and\n",
+ "compare this with the functionality included in **Scikit-Learn**. \n",
+ "\n",
+ "The code here outlines some of the elements we could include in the\n",
+ "analysis. Feel free to extend upon this in order to address the above\n",
+ "questions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# diagonalize and obtain eigenvalues, not necessarily sorted\n",
+ "EigValues, EigVectors = np.linalg.eig(Cov)\n",
+ "# sort eigenvectors and eigenvalues\n",
+ "#permute = EigValues.argsort()\n",
+ "#EigValues = EigValues[permute]\n",
+ "#EigVectors = EigVectors[:,permute]\n",
+ "print(\"Eigenvalues of Covariance matrix\")\n",
+ "for i in range(2):\n",
+ " print(EigValues[i])\n",
+ "FirstEigvector = EigVectors[:,0]\n",
+ "SecondEigvector = EigVectors[:,1]\n",
+ "print(\"First eigenvector\")\n",
+ "print(FirstEigvector)\n",
+ "print(\"Second eigenvector\")\n",
+ "print(SecondEigvector)\n",
+ "#thereafter we do a PCA with Scikit-learn\n",
+ "from sklearn.decomposition import PCA\n",
+ "pca = PCA(n_components = 2)\n",
+ "X2Dsl = pca.fit_transform(X)\n",
+ "print(\"Eigenvector of largest eigenvalue\")\n",
+ "print(pca.components_.T[:, 0])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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? \n",
+ "\n",
+ "\n",
+ "## Classical PCA Theorem\n",
+ "\n",
+ "We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n",
+ "centered as discussed above. For the sake of simplicity we skip the\n",
+ "overline symbol. The matrix is defined in terms of the various column\n",
+ "vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n",
+ "$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The PCA theorem states that minimizing the above reconstruction error\n",
+ "corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n",
+ "diagonalizes the empirical covariance(correlation) matrix. The optimal\n",
+ "low-dimensional encoding of the data is then given by a set of vectors\n",
+ "$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n",
+ "orthogonal projection of the data onto the columns spanned by the\n",
+ "eigenvectors of the covariance(correlations matrix).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "To show the PCA theorem let us start with the assumption that there is one vector $\\boldsymbol{s}_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 $\\boldsymbol{w}_0$ and $\\boldsymbol{z}_0$ as\n",
+ "\n",
+ "\n",
+ "\n",
+ "We are almost there, we have obtained a relation between minimizing\n",
+ "the reconstruction error and the variance and the covariance\n",
+ "matrix. Minimizing the error is equivalent to maximizing the variance\n",
+ "of the projected data.\n",
+ "\n",
+ "\n",
+ "We could trivially maximize the variance of the projection (and\n",
+ "thereby minimize the error in the reconstruction function) by letting\n",
+ "the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n",
+ "want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n",
+ "$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n",
+ "Lagrange multiplier we can then in turn maximize"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "J(\\boldsymbol{w}_0)= \\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0+\\lambda_0(1-\\boldsymbol{w}_0^T\\boldsymbol{w}_0).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial J(\\boldsymbol{w}_0)}{\\partial \\boldsymbol{w}_0}= 2\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0-2\\lambda_0\\boldsymbol{w}_0=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix**! If we left multiply with $\\boldsymbol{w}_0^T$ we have the variance of the projected data is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we want to maximize the variance (minimize the construction error)\n",
+ "we simply pick the eigenvector of the covariance matrix with the\n",
+ "largest eigenvalue. This establishes the link between the minimization\n",
+ "of the reconstruction function $J$ in terms of an orthogonal matrix\n",
+ "and the maximization of the variance and thereby the covariance of our\n",
+ "observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n",
+ "\n",
+ "The proof\n",
+ "for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n",
+ "established by applying the above arguments and using the fact that\n",
+ "our basis of eigenvectors is orthogonal, see [Murphy chapter\n",
+ "12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n",
+ "discussion in chapter 12.2 of Murphy's text has also a nice link with\n",
+ "the Singular Value Decomposition theorem. For categorical data, see\n",
+ "chapter 12.4 and discussion therein.\n",
+ "\n",
+ "For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102).\n",
+ "\n",
+ "\n",
+ "## Geometric Interpretation and link with Singular Value Decomposition\n",
+ "\n",
+ "For a detailed demonstration of the geometric interpretation, see [Vidal, Ma and Sastry, section 2.1.2](https://www.springer.com/gp/book/9780387878102).\n",
+ "\n",
+ "\n",
+ "Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n",
+ "First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n",
+ "\n",
+ "The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n",
+ "training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "from IPython.display import display\n",
+ "np.random.seed(100)\n",
+ "# setting up a 10 x 5 vanilla matrix \n",
+ "rows = 10\n",
+ "cols = 5\n",
+ "X = np.random.randn(rows,cols)\n",
+ "df = pd.DataFrame(X)\n",
+ "# Pandas does the centering for us\n",
+ "df = df -df.mean()\n",
+ "display(df)\n",
+ "\n",
+ "# we center it ourselves\n",
+ "X_centered = X - X.mean(axis=0)\n",
+ "# Then check the difference between pandas and our own set up\n",
+ "print(X_centered-df)\n",
+ "#Now we do an SVD\n",
+ "U, s, V = np.linalg.svd(X_centered)\n",
+ "c1 = V.T[:, 0]\n",
+ "c2 = V.T[:, 1]\n",
+ "W2 = V.T[:, :2]\n",
+ "X2D = X_centered.dot(W2)\n",
+ "print(X2D)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering\n",
+ "the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t\n",
+ "forget to center the data first.\n",
+ "\n",
+ "Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n",
+ "down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n",
+ "Selecting this hyperplane ensures that the projection will preserve as much variance as possible."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "W2 = V.T[:, :2]\n",
+ "X2D = X_centered.dot(W2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## PCA and scikit-learn\n",
+ "\n",
+ "Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n",
+ "following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n",
+ "that it automatically takes care of centering the data):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "#thereafter we do a PCA with Scikit-learn\n",
+ "from sklearn.decomposition import PCA\n",
+ "pca = PCA(n_components = 2)\n",
+ "X2D = pca.fit_transform(X)\n",
+ "print(X2D)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "After fitting the PCA transformer to the dataset, you can access the principal components using the\n",
+ "components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n",
+ "principal component is equal to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pca.components_.T[:, 0]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Another very useful piece of information is the explained variance ratio of each principal component,\n",
+ "available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n",
+ "variance that lies along the axis of each principal component. \n",
+ "\n",
+ "## Back to the Cancer Data\n",
+ "We can now repeat the above but applied to real data, in this case our breast cancer data.\n",
+ "Here we compute performance scores on the training data using logistic regression."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "\n",
+ "logreg = LogisticRegression()\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n",
+ "# We scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\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",
+ "# Then perform again a log reg fit\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n",
+ "#thereafter we do a PCA with Scikit-learn\n",
+ "from sklearn.decomposition import PCA\n",
+ "pca = PCA(n_components = 2)\n",
+ "X2D_train = pca.fit_transform(X_train_scaled)\n",
+ "# and finally compute the log reg fit and the score on the training data\t\n",
+ "logreg.fit(X2D_train,y_train)\n",
+ "print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n",
+ "\n",
+ "\n",
+ "Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n",
+ "choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n",
+ "Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n",
+ "generally want to reduce the dimensionality down to 2 or 3.\n",
+ "The following code computes PCA without reducing dimensionality, then computes the minimum number\n",
+ "of dimensions required to preserve 95% of the training set’s variance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pca = PCA()\n",
+ "pca.fit(X)\n",
+ "cumsum = np.cumsum(pca.explained_variance_ratio_)\n",
+ "d = np.argmax(cumsum >= 0.95) + 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n",
+ "of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n",
+ "a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pca = PCA(n_components=0.95)\n",
+ "X_reduced = pca.fit_transform(X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Incremental PCA\n",
+ "\n",
+ "One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n",
+ "memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n",
+ "been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n",
+ "at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n",
+ "instances arrive).\n",
+ "\n",
+ "\n",
+ "### Randomized PCA\n",
+ "\n",
+ "Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n",
+ "algorithm that quickly finds an approximation of the first d principal components. Its computational\n",
+ "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\n",
+ "previous algorithms when $d$ is much smaller than $n$.\n",
+ "\n",
+ "\n",
+ "### Kernel PCA\n",
+ "\n",
+ "The kernel trick is a mathematical technique that implicitly maps instances into a\n",
+ "very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n",
+ "with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n",
+ "space corresponds to a complex nonlinear decision boundary in the original space.\n",
+ "It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n",
+ "projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n",
+ "preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n",
+ "twisted manifold.\n",
+ "For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.decomposition import KernelPCA\n",
+ "rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n",
+ "X_reduced = rbf_pca.fit_transform(X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other techniques\n",
+ "\n",
+ "\n",
+ "There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n",
+ "\n",
+ "Here are some of the most popular:\n",
+ "* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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).\n",
+ "\n",
+ "* 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."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapter9.ipynb b/doc/LectureNotes/_build/html/_sources/chapter9.ipynb
new file mode 100644
index 000000000..89b5cbf54
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapter9.ipynb
@@ -0,0 +1,1283 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Neural networks\n",
+ "\n",
+ "Artificial neural networks are computational systems that can learn to\n",
+ "perform tasks by considering examples, generally without being\n",
+ "programmed with any task-specific rules. It is supposed to mimic a\n",
+ "biological system, wherein neurons interact by sending signals in the\n",
+ "form of mathematical functions between layers. All layers can contain\n",
+ "an arbitrary number of neurons, and each connection is represented by\n",
+ "a weight variable.\n",
+ "\n",
+ "\n",
+ "The field of artificial neural networks has a long history of\n",
+ "development, and is closely connected with the advancement of computer\n",
+ "science and computers in general. A model of artificial neurons was\n",
+ "first developed by McCulloch and Pitts in 1943 to study signal\n",
+ "processing in the brain and has later been refined by others. The\n",
+ "general idea is to mimic neural networks in the human brain, which is\n",
+ "composed of billions of neurons that communicate with each other by\n",
+ "sending electrical signals. Each neuron accumulates its incoming\n",
+ "signals, which must exceed an activation threshold to yield an\n",
+ "output. If the threshold is not overcome, the neuron remains inactive,\n",
+ "i.e. has zero output.\n",
+ "\n",
+ "This behaviour has inspired a simple mathematical model for an artificial neuron."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n",
+ "\\label{artificialNeuron} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n",
+ "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n",
+ "\n",
+ "Conceptually, it is helpful to divide neural networks into four\n",
+ "categories:\n",
+ "1. general purpose neural networks for supervised learning,\n",
+ "\n",
+ "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n",
+ "\n",
+ "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n",
+ "\n",
+ "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n",
+ "\n",
+ "In natural science, DNNs and CNNs have already found numerous\n",
+ "applications. In statistical physics, they have been applied to detect\n",
+ "phase transitions in 2D Ising and Potts models, lattice gauge\n",
+ "theories, and different phases of polymers, or solving the\n",
+ "Navier-Stokes equation in weather forecasting. Deep learning has also\n",
+ "found interesting applications in quantum physics. Various quantum\n",
+ "phase transitions can be detected and studied using DNNs and CNNs,\n",
+ "topological phases, and even non-equilibrium many-body\n",
+ "localization. Representing quantum states as DNNs quantum state\n",
+ "tomography are among some of the impressive achievements to reveal the\n",
+ "potential of DNNs to facilitate the study of quantum systems.\n",
+ "\n",
+ "In quantum information theory, it has been shown that one can perform\n",
+ "gate decompositions with the help of neural. \n",
+ "\n",
+ "The applications are not limited to the natural sciences. There is a\n",
+ "plethora of applications in essentially all disciplines, from the\n",
+ "humanities to life science and medicine.\n",
+ "\n",
+ "\n",
+ "An artificial neural network (ANN), is a computational model that\n",
+ "consists of layers of connected neurons, or nodes or units. We will\n",
+ "refer to these interchangeably as units or nodes, and sometimes as\n",
+ "neurons.\n",
+ "\n",
+ "It is supposed to mimic a biological nervous system by letting each\n",
+ "neuron interact with other neurons by sending signals in the form of\n",
+ "mathematical functions between layers. A wide variety of different\n",
+ "ANNs have been developed, but most of them consist of an input layer,\n",
+ "an output layer and eventual layers in-between, called *hidden\n",
+ "layers*. All layers can contain an arbitrary number of nodes, and each\n",
+ "connection between two nodes is associated with a weight variable.\n",
+ "\n",
+ "Neural networks (also called neural nets) are neural-inspired\n",
+ "nonlinear models for supervised learning. As we will see, neural nets\n",
+ "can be viewed as natural, more powerful extensions of supervised\n",
+ "learning methods such as linear and logistic regression and soft-max\n",
+ "methods we discussed earlier.\n",
+ "\n",
+ "\n",
+ "### Feed-forward neural networks\n",
+ "\n",
+ "The feed-forward neural network (FFNN) was the first and simplest type\n",
+ "of ANNs that were devised. In this network, the information moves in\n",
+ "only one direction: forward through the layers.\n",
+ "\n",
+ "Nodes are represented by circles, while the arrows display the\n",
+ "connections between the nodes, including the direction of information\n",
+ "flow. Additionally, each arrow corresponds to a weight variable\n",
+ "(figure to come). We observe that each node in a layer is connected\n",
+ "to *all* nodes in the subsequent layer, making this a so-called\n",
+ "*fully-connected* FFNN.\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Convolutional Neural Network\n",
+ "\n",
+ "A different variant of FFNNs are *convolutional neural networks*\n",
+ "(CNNs), which have a connectivity pattern inspired by the animal\n",
+ "visual cortex. Individual neurons in the visual cortex only respond to\n",
+ "stimuli from small sub-regions of the visual field, called a receptive\n",
+ "field. This makes the neurons well-suited to exploit the strong\n",
+ "spatially local correlation present in natural images. The response of\n",
+ "each neuron can be approximated mathematically as a convolution\n",
+ "operation. (figure to come)\n",
+ "\n",
+ "Convolutional neural networks emulate the behaviour of neurons in the\n",
+ "visual cortex by enforcing a *local* connectivity pattern between\n",
+ "nodes of adjacent layers: Each node in a convolutional layer is\n",
+ "connected only to a subset of the nodes in the previous layer, in\n",
+ "contrast to the fully-connected FFNN. Often, CNNs consist of several\n",
+ "convolutional layers that learn local features of the input, with a\n",
+ "fully-connected layer at the end, which gathers all the local data and\n",
+ "produces the outputs. They have wide applications in image and video\n",
+ "recognition.\n",
+ "\n",
+ "### Recurrent neural networks\n",
+ "\n",
+ "So far we have only mentioned ANNs where information flows in one\n",
+ "direction: forward. *Recurrent neural networks* on the other hand,\n",
+ "have connections between nodes that form directed *cycles*. This\n",
+ "creates a form of internal memory which are able to capture\n",
+ "information on what has been calculated before; the output is\n",
+ "dependent on the previous computations. Recurrent NNs make use of\n",
+ "sequential information by performing the same task for every element\n",
+ "in a sequence, where each element depends on previous elements. An\n",
+ "example of such information is sentences, making recurrent NNs\n",
+ "especially well-suited for handwriting and speech recognition.\n",
+ "\n",
+ "### Other types of networks\n",
+ "\n",
+ "There are many other kinds of ANNs that have been developed. One type\n",
+ "that is specifically designed for interpolation in multidimensional\n",
+ "space is the radial basis function (RBF) network. RBFs are typically\n",
+ "made up of three layers: an input layer, a hidden layer with\n",
+ "non-linear radial symmetric activation functions and a linear output\n",
+ "layer (''linear'' here means that each node in the output layer has a\n",
+ "linear activation function). The layers are normally fully-connected\n",
+ "and there are no cycles, thus RBFs can be viewed as a type of\n",
+ "fully-connected FFNN. They are however usually treated as a separate\n",
+ "type of NN due the unusual activation functions.\n",
+ "\n",
+ "\n",
+ "## Multilayer perceptrons\n",
+ "\n",
+ "One uses often so-called fully-connected feed-forward neural networks\n",
+ "with three or more layers (an input layer, one or more hidden layers\n",
+ "and an output layer) consisting of neurons that have non-linear\n",
+ "activation functions.\n",
+ "\n",
+ "Such networks are often called *multilayer perceptrons* (MLPs).\n",
+ "\n",
+ "\n",
+ "According to the *Universal approximation theorem*, a feed-forward\n",
+ "neural network with just a single hidden layer containing a finite\n",
+ "number of neurons can approximate a continuous multidimensional\n",
+ "function to arbitrary accuracy, assuming the activation function for\n",
+ "the hidden layer is a **non-constant, bounded and\n",
+ "monotonically-increasing continuous function**.\n",
+ "\n",
+ "Note that the requirements on the activation function only applies to\n",
+ "the hidden layer, the output nodes are always assumed to be linear, so\n",
+ "as to not restrict the range of output values.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The output $y$ is produced via the activation function $f$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This function receives $x_i$ as inputs.\n",
+ "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n",
+ "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n",
+ "the neurons in the preceding layer. Furthermore, an MLP is\n",
+ "fully-connected, which means that each neuron receives a weighted sum\n",
+ "of the outputs of *all* neurons in the previous layer.\n",
+ "\n",
+ "\n",
+ "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n",
+ "\\label{_auto1} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here $b_i$ is the so-called bias which is normally needed in\n",
+ "case of zero activation weights or inputs. How to fix the biases and\n",
+ "the weights will be discussed below. The value of $z_i^1$ is the\n",
+ "argument to the activation function $f_i$ of each node $i$, The\n",
+ "variable $M$ stands for all possible inputs to a given node $i$ in the\n",
+ "first layer. We define the output $y_i^1$ of all neurons in layer 1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n",
+ "\\label{outputLayer1} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we assume that all nodes in the same layer have identical\n",
+ "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n",
+ "In this case we would identify these functions with a superscript $l$ for the $l$-th layer,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " 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)\n",
+ "\\label{generalLayer} \\tag{4}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $N_l$ is the number of nodes in layer $l$. When the output of\n",
+ "all the nodes in the first hidden layer are computed, the values of\n",
+ "the subsequent layer can be calculated and so forth until the output\n",
+ "is obtained.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "The output of neuron $i$ in layer 2 is thus,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n",
+ "\\label{_auto2} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ " = 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]\n",
+ "\\label{outputLayer2} \\tag{6}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n",
+ "\\label{_auto3} \\tag{7}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ " = 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)\n",
+ " + b_1^3\\right]\n",
+ "\\label{_auto4} \\tag{8}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can generalize this expression to an MLP with $l$ hidden\n",
+ "layers. The complete functional form is,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "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] \n",
+ "\\label{completeNN} \\tag{9}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which illustrates a basic property of MLPs: The only independent\n",
+ "variables are the input values $x_n$.\n",
+ "\n",
+ "\n",
+ "This confirms that an MLP, despite its quite convoluted mathematical\n",
+ "form, is nothing more than an analytic function, specifically a\n",
+ "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n",
+ "\\hat{y} \\in \\mathbb{R}^m$.\n",
+ "\n",
+ "Furthermore, the flexibility and universality of an MLP can be\n",
+ "illustrated by realizing that the expression is essentially a nested\n",
+ "sum of scaled activation functions of the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " f(x) = c_1 f(c_2 x + c_3) + c_4\n",
+ "\\label{_auto5} \\tag{10}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the parameters $c_i$ are weights and biases. By adjusting these\n",
+ "parameters, the activation functions can be shifted up and down or\n",
+ "left and right, change slope or be rescaled which is the key to the\n",
+ "flexibility of a neural network.\n",
+ "\n",
+ "\n",
+ "We can introduce a more convenient notation for the activations in an A NN. \n",
+ "\n",
+ "Additionally, we can represent the biases and activations\n",
+ "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n",
+ "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n",
+ "\n",
+ "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. \n",
+ "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n",
+ "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n",
+ " f_2\\left(\\left[\\begin{array}{ccc}\n",
+ " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n",
+ " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n",
+ " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n",
+ " \\end{array} \\right] \\cdot\n",
+ " \\left[\\begin{array}{c}\n",
+ " y^1_1 \\\\\n",
+ " y^1_2 \\\\\n",
+ " y^1_3 \\\\\n",
+ " \\end{array}\\right] + \n",
+ " \\left[\\begin{array}{c}\n",
+ " b^2_1 \\\\\n",
+ " b^2_2 \\\\\n",
+ " b^2_3 \\\\\n",
+ " \\end{array}\\right]\\right).\n",
+ "\\label{_auto6} \\tag{11}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Matrix-vector notation and activation\n",
+ "\n",
+ "The activation of node $i$ in layer 2 is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " 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) = \n",
+ " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n",
+ "\\label{_auto7} \\tag{12}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is not just a convenient and compact notation, but also a useful\n",
+ "and intuitive way to think about MLPs: The output is calculated by a\n",
+ "series of matrix-vector multiplications and vector additions that are\n",
+ "used as input to the activation functions. For each operation\n",
+ "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "### Activation functions\n",
+ "\n",
+ "A property that characterizes a neural network, other than its\n",
+ "connectivity, is the choice of activation function(s). As described\n",
+ "in, the following restrictions are imposed on an activation function\n",
+ "for a FFNN to fulfill the universal approximation theorem\n",
+ "\n",
+ " * Non-constant\n",
+ "\n",
+ " * Bounded\n",
+ "\n",
+ " * Monotonically-increasing\n",
+ "\n",
+ " * Continuous\n",
+ "\n",
+ "The second requirement excludes all linear functions. Furthermore, in\n",
+ "a MLP with only linear activation functions, each layer simply\n",
+ "performs a linear transformation of its inputs.\n",
+ "\n",
+ "Regardless of the number of layers, the output of the NN will be\n",
+ "nothing but a linear function of the inputs. Thus we need to introduce\n",
+ "some kind of non-linearity to the NN to be able to fit non-linear\n",
+ "functions Typical examples are the logistic *Sigmoid*"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(x) = \\frac{1}{1 + e^{-x}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the *hyperbolic tangent* function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(x) = \\tanh(x)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The *sigmoid* function are more biologically plausible because the\n",
+ "output of inactive neurons are zero. Such activation function are\n",
+ "called *one-sided*. However, it has been shown that the hyperbolic\n",
+ "tangent performs better than the sigmoid for training MLPs. has\n",
+ "become the most popular for *deep neural networks*"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "\"\"\"The sigmoid function (or the logistic curve) is a \n",
+ "function that takes any real number, z, and outputs a number (0,1).\n",
+ "It is useful in neural networks for assigning weights on a relative scale.\n",
+ "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n",
+ "\n",
+ "import numpy\n",
+ "import matplotlib.pyplot as plt\n",
+ "import math as mt\n",
+ "\n",
+ "z = numpy.arange(-5, 5, .1)\n",
+ "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n",
+ "sigma = sigma_fn(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, sigma)\n",
+ "ax.set_ylim([-0.1, 1.1])\n",
+ "ax.set_xlim([-5,5])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('sigmoid function')\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\"\"\"Step Function\"\"\"\n",
+ "z = numpy.arange(-5, 5, .02)\n",
+ "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n",
+ "step = step_fn(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, step)\n",
+ "ax.set_ylim([-0.5, 1.5])\n",
+ "ax.set_xlim([-5,5])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('step function')\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\"\"\"Sine Function\"\"\"\n",
+ "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n",
+ "t = numpy.sin(z)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, t)\n",
+ "ax.set_ylim([-1.0, 1.0])\n",
+ "ax.set_xlim([-2*mt.pi,2*mt.pi])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('sine function')\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "\"\"\"Plots a graph of the squashing function used by a rectified linear\n",
+ "unit\"\"\"\n",
+ "z = numpy.arange(-2, 2, .1)\n",
+ "zero = numpy.zeros(len(z))\n",
+ "y = numpy.max([zero, z], axis=0)\n",
+ "\n",
+ "fig = plt.figure()\n",
+ "ax = fig.add_subplot(111)\n",
+ "ax.plot(z, y)\n",
+ "ax.set_ylim([-2.0, 2.0])\n",
+ "ax.set_xlim([-2.0, 2.0])\n",
+ "ax.grid(True)\n",
+ "ax.set_xlabel('z')\n",
+ "ax.set_title('Rectified linear unit')\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The multilayer perceptron (MLP)\n",
+ "\n",
+ "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n",
+ "1. A neural network with one or more layers of nodes between the input and the output nodes.\n",
+ "\n",
+ "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n",
+ "\n",
+ "3. 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.\n",
+ "\n",
+ "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n",
+ "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.\n",
+ "\n",
+ "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n",
+ "Hereafter we will call the various entities of a layer for nodes.\n",
+ "There are also no connections within a single layer.\n",
+ "\n",
+ "The number of input nodes does not need to equal the number of output\n",
+ "nodes. This applies also to the hidden layers. Each layer may have its\n",
+ "own number of nodes and activation functions.\n",
+ "\n",
+ "The hidden layers have their name from the fact that they are not\n",
+ "linked to observables and as we will see below when we define the\n",
+ "so-called activation $\\hat{z}$, we can think of this as a basis\n",
+ "expansion of the original inputs $\\hat{x}$. The difference however\n",
+ "between neural networks and say linear regression is that now these\n",
+ "basis functions (which will correspond to the weights in the network)\n",
+ "are learned from data. This results in an important difference between\n",
+ "neural networks and deep learning approaches on one side and methods\n",
+ "like logistic regression or linear regression and their modifications on the other side.\n",
+ "\n",
+ "\n",
+ "### From one to many layers, the universal approximation theorem\n",
+ "\n",
+ "A neural network with only one layer, what we called the simple\n",
+ "perceptron, is best suited if we have a standard binary model with\n",
+ "clear (linear) boundaries between the outcomes. As such it could\n",
+ "equally well be replaced by standard linear regression or logistic\n",
+ "regression. Networks with one or more hidden layers approximate\n",
+ "systems with more complex boundaries.\n",
+ "\n",
+ "As stated earlier, \n",
+ "an important theorem in studies of neural networks, restated without\n",
+ "proof here, is the [universal approximation\n",
+ "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n",
+ "\n",
+ "It states that a feed-forward network with a single hidden layer\n",
+ "containing a finite number of neurons can approximate continuous\n",
+ "functions on compact subsets of real functions. The theorem thus\n",
+ "states that simple neural networks can represent a wide variety of\n",
+ "interesting functions when given appropriate parameters. It is the\n",
+ "multilayer feedforward architecture itself which gives neural networks\n",
+ "the potential of being universal approximators.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Deriving the back propagation code for a multilayer perceptron model\n",
+ "\n",
+ "\n",
+ "\n",
+ "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.\n",
+ "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.\n",
+ "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n",
+ "\n",
+ "The questions we want to ask are how do changes in the biases and the\n",
+ "weights in our network change the cost function and how can we use the\n",
+ "final output to modify the weights?\n",
+ "\n",
+ "To derive these equations let us start with a plain regression problem\n",
+ "and define our cost function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the $t_i$s are our $n$ targets (the values we want to\n",
+ "reproduce), while the outputs of the network after having propagated\n",
+ "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n",
+ "how the basic equations arising from the back propagation algorithm\n",
+ "can be modified in order to study classification problems with $K$\n",
+ "classes.\n",
+ "\n",
+ "\n",
+ "With our definition of the targets $\\hat{t}$, the outputs of the\n",
+ "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n",
+ "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n",
+ "$l$-th layer as a function of the bias, the weights which add up from\n",
+ "the previous layer $l-1$ and the forward passes/outputs\n",
+ "$\\hat{a}^{l-1}$ from the previous layer as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n",
+ "represents the total number of nodes/neurons/units of layer $l-1$. The\n",
+ "figure here illustrates this equation. We can rewrite this in a more\n",
+ "compact form as the matrix-vector products we discussed earlier,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With the activation values $\\hat{z}^l$ we can in turn define the\n",
+ "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n",
+ "activation function. In the examples here we will use the sigmoid\n",
+ "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n",
+ "and their nodes. It means we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Derivatives and the chain rule\n",
+ "\n",
+ "From the definition of the activation $z_j^l$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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)).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n",
+ "\n",
+ "Let us specialize to the output layer $l=L$. Our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The derivative of this function with respect to the weights is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The last partial derivative can easily be computed and reads (by applying the chain rule)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Bringing it together, first back propagation equation\n",
+ "\n",
+ "We have thus"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using the Hadamard product of two vectors we can write this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is an important expression. The second term on the right handside\n",
+ "measures how fast the cost function is changing as a function of the $j$th\n",
+ "output activation. If, for example, the cost function doesn't depend\n",
+ "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n",
+ "which is what we would expect. The first term on the right, measures\n",
+ "how fast the activation function $f$ is changing at a given activation\n",
+ "value $z_j^L$.\n",
+ "\n",
+ "Notice that everything in the above equations is easily computed. In\n",
+ "particular, we compute $z_j^L$ while computing the behaviour of the\n",
+ "network, and it is only a small additional overhead to compute\n",
+ "$f'(z^L_j)$. The exact form of the derivative with respect to the\n",
+ "output depends on the form of the cost function.\n",
+ "However, provided the cost function is known there should be little\n",
+ "trouble in calculating"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is also easy to see that our previous equation can be written as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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. \n",
+ "\n",
+ "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\n",
+ "\n",
+ "**The starting equations.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n",
+ "\\label{_auto8} \\tag{13}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n",
+ "\\label{_auto9} \\tag{14}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n",
+ "\\label{_auto10} \\tag{15}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "An interesting consequence of the above equations is that when the\n",
+ "activation $a_k^{L-1}$ is small, the gradient term, that is the\n",
+ "derivative of the cost function with respect to the weights, will also\n",
+ "tend to be small. We say then that the weight learns slowly, meaning\n",
+ "that it changes slowly when we minimize the weights via say gradient\n",
+ "descent. In this case we say the system learns slowly.\n",
+ "\n",
+ "Another interesting feature is that is when the activation function,\n",
+ "represented by the sigmoid function here, is rather flat when we move towards\n",
+ "its end values $0$ and $1$ (see the above Python codes). In these\n",
+ "cases, the derivatives of the activation function will also be close\n",
+ "to zero, meaning again that the gradients will be small and the\n",
+ "network learns slowly again.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We need a fourth equation and we are set. We are going to propagate\n",
+ "backwards in order to the determine the weights and biases. In order\n",
+ "to do so we need to represent the error in the layer before the final\n",
+ "one $L-1$ in terms of the errors in the final output layer.\n",
+ "\n",
+ "### Final back propagating equation\n",
+ "\n",
+ "We have that (replacing $L$ with a general layer $l$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and recalling that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $M_l$ being the number of nodes in layer $l$, we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is our final equation.\n",
+ "\n",
+ "We are now ready to set up the algorithm for back propagation and learning the weights and biases.\n",
+ "\n",
+ "\n",
+ "### Setting up the Back propagation algorithm\n",
+ "\n",
+ "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.\n",
+ "\n",
+ "First, we set up the input data $\\hat{x}$ and the activations\n",
+ "$\\hat{z}_1$ of the input layer and compute the activation function and\n",
+ "the pertinent outputs $\\hat{a}^1$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Secondly, we perform then the feed forward till we reach the output\n",
+ "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n",
+ "activation function and the pertinent outputs $\\hat{a}^l$ for\n",
+ "$l=2,3,\\dots,L$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n",
+ "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."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/chapteroptimization.ipynb b/doc/LectureNotes/_build/html/_sources/chapteroptimization.ipynb
new file mode 100644
index 000000000..e8dc9fc17
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/chapteroptimization.ipynb
@@ -0,0 +1,2793 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Optimization, the central part of any Machine Learning algortithm\n",
+ "\n",
+ "Almost every problem in machine learning and data science starts with\n",
+ "a dataset $X$, a model $g(\\beta)$, which is a function of the\n",
+ "parameters $\\beta$ and a cost function $C(X, g(\\beta))$ that allows\n",
+ "us to judge how well the model $g(\\beta)$ explains the observations\n",
+ "$X$. The model is fit by finding the values of $\\beta$ that minimize\n",
+ "the cost function. Ideally we would be able to solve for $\\beta$\n",
+ "analytically, however this is not possible in general and we must use\n",
+ "some approximative/numerical method to compute the minimum.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our discussion on Logistic Regression we studied the \n",
+ "case of\n",
+ "two classes, with $y_i$ either\n",
+ "$0$ or $1$. Furthermore we assumed also that we have only two\n",
+ "parameters $\\beta$ in our fitting, that is we\n",
+ "defined probabilities"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "p(y_i=1|x_i,\\boldsymbol{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n",
+ "p(y_i=0|x_i,\\boldsymbol{\\beta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\beta}),\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Our compact equations used a definition of a vector $\\boldsymbol{y}$ with $n$\n",
+ "elements $y_i$, an $n\\times p$ matrix $\\boldsymbol{X}$ which contains the\n",
+ "$x_i$ values and a vector $\\boldsymbol{p}$ of fitted probabilities\n",
+ "$p(y_i\\vert x_i,\\boldsymbol{\\beta})$. We rewrote in a more compact form\n",
+ "the first derivative of the cost function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n",
+ "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This defines what is called the Hessian matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "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. \n",
+ "\n",
+ "Our iterative scheme is then given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\right)^{-1}_{\\boldsymbol{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}\\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or in matrix form as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X} \\right)^{-1}\\times \\left(-\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{p}) \\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The right-hand side is computed with the old values of $\\beta$. \n",
+ "\n",
+ "If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. \n",
+ "\n",
+ "\n",
+ "Let us quickly remind ourselves how we derive the above method.\n",
+ "\n",
+ "Perhaps the most celebrated of all one-dimensional root-finding\n",
+ "routines is Newton's method, also called the Newton-Raphson\n",
+ "method. This method requires the evaluation of both the\n",
+ "function $f$ and its derivative $f'$ at arbitrary points. \n",
+ "If you can only calculate the derivative\n",
+ "numerically and/or your function is not of the smooth type, we\n",
+ "normally discourage the use of this method.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The Newton-Raphson formula consists geometrically of extending the\n",
+ "tangent line at a current point until it crosses zero, then setting\n",
+ "the next guess to the abscissa of that zero-crossing. The mathematics\n",
+ "behind this method is rather simple. Employing a Taylor expansion for\n",
+ "$x$ sufficiently close to the solution $s$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "f(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n",
+ " \\label{eq:taylornr} \\tag{1}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For small enough values of the function and for well-behaved\n",
+ "functions, the terms beyond linear are unimportant, hence we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(x)+(s-x)f'(x)\\approx 0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "yielding"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "s\\approx x-\\frac{f(x)}{f'(x)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Having in mind an iterative procedure, it is natural to start iterating with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The above is Newton-Raphson's method. It has a simple geometric\n",
+ "interpretation, namely $x_{n+1}$ is the point where the tangent from\n",
+ "$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\n",
+ "Newton-Raphson converges fast to the desired result. However, if we\n",
+ "are far from a root, where the higher-order terms in the series are\n",
+ "important, the Newton-Raphson formula can give grossly inaccurate\n",
+ "results. For instance, the initial guess for the root might be so far\n",
+ "from the true root as to let the search interval include a local\n",
+ "maximum or minimum of the function. If an iteration places a trial\n",
+ "guess near such a local extremum, so that the first derivative nearly\n",
+ "vanishes, then Newton-Raphson may fail totally\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Newton's method can be generalized to systems of several non-linear equations\n",
+ "and variables. Consider the case with two equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n",
+ " f_2(x_1,x_2) &=0,\\end{array}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we Taylor expand to obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n",
+ " \\partial f_1/\\partial x_1+h_2\n",
+ " \\partial f_1/\\partial x_2+\\dots\\\\\n",
+ " 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1\n",
+ " \\partial f_2/\\partial x_1+h_2\n",
+ " \\partial f_2/\\partial x_2+\\dots\n",
+ " \\end{array}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Defining the Jacobian matrix $\\boldsymbol{J}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{J}=\\left( \\begin{array}{cc}\n",
+ " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n",
+ " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n",
+ " \\end{array} \\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rephrase Newton's method as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n",
+ "\\left(\\begin{array}{c} x_1^{n} \\\\ x_2^{n} \\end{array} \\right)+\n",
+ "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n",
+ " -\\boldsymbol{J}^{-1}\n",
+ " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need thus to compute the inverse of the Jacobian matrix and it\n",
+ "is to understand that difficulties may\n",
+ "arise in case $\\boldsymbol{J}$ is nearly singular.\n",
+ "\n",
+ "It is rather straightforward to extend the above scheme to systems of\n",
+ "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. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Steepest descent\n",
+ "\n",
+ "The basic idea of gradient descent is\n",
+ "that a function $F(\\mathbf{x})$, \n",
+ "$\\mathbf{x} \\equiv (x_1,\\cdots,x_n)$, decreases fastest if one goes from $\\bf {x}$ in the\n",
+ "direction of the negative gradient $-\\nabla F(\\mathbf{x})$.\n",
+ "\n",
+ "It can be shown that if"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\gamma_k > 0$.\n",
+ "\n",
+ "For $\\gamma_k$ small enough, then $F(\\mathbf{x}_{k+1}) \\leq\n",
+ "F(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\n",
+ "we are always moving towards smaller function values, i.e a minimum.\n",
+ "\n",
+ "\n",
+ "The previous observation is the basis of the method of steepest\n",
+ "descent, which is also referred to as just gradient descent (GD). One\n",
+ "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n",
+ "computes new approximations according to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The parameter $\\gamma_k$ is often referred to as the step length or\n",
+ "the learning rate within the context of Machine Learning.\n",
+ "\n",
+ "\n",
+ "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n",
+ "minimum of the function $F$. In general we do not know if we are in a\n",
+ "global or local minimum. In the special case when $F$ is a convex\n",
+ "function, all local minima are also global minima, so in this case\n",
+ "gradient descent can converge to the global solution. The advantage of\n",
+ "this scheme is that it is conceptually simple and straightforward to\n",
+ "implement. However the method in this form has some severe\n",
+ "limitations:\n",
+ "\n",
+ "In machine learing we are often faced with non-convex high dimensional\n",
+ "cost functions with many local minima. Since GD is deterministic we\n",
+ "will get stuck in a local minimum, if the method converges, unless we\n",
+ "have a very good intial guess. This also implies that the scheme is\n",
+ "sensitive to the chosen initial condition.\n",
+ "\n",
+ "Note that the gradient is a function of $\\mathbf{x} =\n",
+ "(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "The gradient descent method \n",
+ "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n",
+ "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n",
+ "F(\\mathbf{x}_k)$ for sufficiently small $\\gamma_k$. The problem is to\n",
+ "determine an optimal learning rate. If the learning rate is chosen too\n",
+ "small the method will take a long time to converge and if it is too\n",
+ "large we can experience erratic behavior.\n",
+ "\n",
+ "Many of these shortcomings can be alleviated by introducing\n",
+ "randomness. One such method is that of Stochastic Gradient Descent\n",
+ "(SGD), see below.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Convex functions\n",
+ "\n",
+ "Ideally we want our cost/loss function to be convex(concave).\n",
+ "\n",
+ "First we give the definition of a convex set: A set $C$ in\n",
+ "$\\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and\n",
+ "all $t \\in (0,1)$ , the point $(1 − t)x + ty$ also belongs to\n",
+ "C. Geometrically this means that every point on the line segment\n",
+ "connecting $x$ and $y$ is in $C$ as discussed below.\n",
+ "\n",
+ "The convex subsets of $\\mathbb{R}$ are the intervals of\n",
+ "$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\n",
+ "regular polygons (triangles, rectangles, pentagons, etc...).\n",
+ "\n",
+ "\n",
+ "\n",
+ "**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.\n",
+ "\n",
+ "\n",
+ "In the following we state first and second-order conditions which\n",
+ "ensures convexity of a function $f$. We write $D_f$ to denote the\n",
+ "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n",
+ "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n",
+ "\n",
+ "**First order condition.**\n",
+ "\n",
+ "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n",
+ "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n",
+ "is a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\n",
+ "for all $x,y \\in D_f$. This condition means that for a convex function\n",
+ "the first order Taylor expansion (right hand side above) at any point\n",
+ "a global under estimator of the function. To convince yourself you can\n",
+ "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n",
+ "note that it is always below the graph.\n",
+ "\n",
+ "\n",
+ "\n",
+ "**Second order condition.**\n",
+ "\n",
+ "Assume that $f$ is twice\n",
+ "differentiable, i.e the Hessian matrix exists at each point in\n",
+ "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n",
+ "Hessian is positive semi-definite for all $x\\in D_f$. For a\n",
+ "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n",
+ "everywhere.\n",
+ "\n",
+ "\n",
+ "\n",
+ "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.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The next result is of great importance to us and the reason why we are\n",
+ "going on about convex functions. In machine learning we frequently\n",
+ "have to minimize a loss/cost function in order to find the best\n",
+ "parameters for the model we are considering. \n",
+ "\n",
+ "Ideally we want the\n",
+ "global minimum (for high-dimensional models it is hard to know\n",
+ "if we have local or global minimum). However, if the cost/loss function\n",
+ "is convex the following result provides invaluable information:\n",
+ "\n",
+ "**Any minimum is global for convex functions.**\n",
+ "\n",
+ "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n",
+ "is minimal, where $f$ is convex and differentiable. Then, any point\n",
+ "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n",
+ "\n",
+ "\n",
+ "\n",
+ "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.\n",
+ "\n",
+ "\n",
+ "### Some simple problems\n",
+ "\n",
+ "1. 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$.\n",
+ "\n",
+ "2. Using the second order condition show that the following functions are convex on the specified domain.\n",
+ "\n",
+ " * $f(x) = e^x$ is convex for $x \\in \\mathbb{R}$.\n",
+ "\n",
+ " * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n",
+ "\n",
+ "\n",
+ "3. 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.\n",
+ "\n",
+ "4. A norm is any function that satisfy the following properties\n",
+ "\n",
+ " * $f(\\alpha x) = |\\alpha| f(x)$ for all $\\alpha \\in \\mathbb{R}$.\n",
+ "\n",
+ " * $f(x+y) \\leq f(x) + f(y)$\n",
+ "\n",
+ " * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n",
+ "\n",
+ "\n",
+ "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).\n",
+ "\n",
+ "\n",
+ "## Standard steepest descent\n",
+ "\n",
+ "\n",
+ "Before we proceed, we would like to discuss the approach called the\n",
+ "**standard Steepest descent** (different from the above steepest descent discussion), which again leads to us having to be able\n",
+ "to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).\n",
+ "\n",
+ "[The success of the CG method](https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf)\n",
+ "for finding solutions of non-linear problems is based on the theory\n",
+ "of conjugate gradients for linear systems of equations. It belongs to\n",
+ "the class of iterative methods for solving problems from linear\n",
+ "algebra of the type"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the iterative process we end up with a problem like"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{r}= \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{r}$ is the so-called residual or error in the iterative process.\n",
+ "\n",
+ "When we have found the exact solution, $\\boldsymbol{r}=0$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The residual is zero when we reach the minimum of the quadratic equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(\\boldsymbol{x})=\\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T\\boldsymbol{b},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the constraint that the matrix $\\boldsymbol{A}$ is positive definite and\n",
+ "symmetric. This defines also the Hessian and we want it to be positive definite. \n",
+ "\n",
+ "\n",
+ "We denote the initial guess for $\\boldsymbol{x}$ as $\\boldsymbol{x}_0$. \n",
+ "We can assume without loss of generality that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_0=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or consider the system"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "instead.\n",
+ "\n",
+ "\n",
+ "One can show that the solution $\\boldsymbol{x}$ is also the unique minimizer of the quadratic form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This suggests taking the first basis vector $\\boldsymbol{r}_1$ (see below for definition) \n",
+ "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n",
+ "which equals"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$.\n",
+ "\n",
+ "\n",
+ "We can compute the residual iteratively as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which equals"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_k),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{r}_k,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\alpha_k = \\frac{\\boldsymbol{r}_k^T\\boldsymbol{r}_k}{\\boldsymbol{r}_k^T\\boldsymbol{A}\\boldsymbol{r}_k}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to the iterative scheme"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_{k+1}=\\boldsymbol{x}_k-\\alpha_k\\boldsymbol{r}_{k},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import numpy.linalg as la\n",
+ "\n",
+ "import scipy.optimize as sopt\n",
+ "\n",
+ "import matplotlib.pyplot as pt\n",
+ "from mpl_toolkits.mplot3d import axes3d\n",
+ "\n",
+ "def f(x):\n",
+ " return 0.5*x[0]**2 + 2.5*x[1]**2\n",
+ "\n",
+ "def df(x):\n",
+ " return np.array([x[0], 5*x[1]])\n",
+ "\n",
+ "fig = pt.figure()\n",
+ "ax = fig.gca(projection=\"3d\")\n",
+ "\n",
+ "xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]\n",
+ "fmesh = f(np.array([xmesh, ymesh]))\n",
+ "ax.plot_surface(xmesh, ymesh, fmesh)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And then as countor plot"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pt.axis(\"equal\")\n",
+ "pt.contour(xmesh, ymesh, fmesh)\n",
+ "guesses = [np.array([2, 2./5])]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Find guesses"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "x = guesses[-1]\n",
+ "s = -df(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Run it!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "def f1d(alpha):\n",
+ " return f(x + alpha*s)\n",
+ "\n",
+ "alpha_opt = sopt.golden(f1d)\n",
+ "next_guess = x + alpha_opt * s\n",
+ "guesses.append(next_guess)\n",
+ "print(next_guess)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happened?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "pt.axis(\"equal\")\n",
+ "pt.contour(xmesh, ymesh, fmesh, 50)\n",
+ "it_array = np.array(guesses)\n",
+ "pt.plot(it_array.T[0], it_array.T[1], \"x-\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conjugate gradient method\n",
+ "In the CG method we define so-called conjugate directions and two vectors \n",
+ "$\\boldsymbol{s}$ and $\\boldsymbol{t}$\n",
+ "are said to be\n",
+ "conjugate if"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{s}^T\\boldsymbol{A}\\boldsymbol{t}= 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The philosophy of the CG method is to perform searches in various conjugate directions\n",
+ "of our vectors $\\boldsymbol{x}_i$ obeying the above criterion, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T\\boldsymbol{A}\\boldsymbol{x}_j= 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Two vectors are conjugate if they are orthogonal with respect to \n",
+ "this inner product. Being conjugate is a symmetric relation: if $\\boldsymbol{s}$ is conjugate to $\\boldsymbol{t}$, then $\\boldsymbol{t}$ is conjugate to $\\boldsymbol{s}$.\n",
+ "\n",
+ "An example is given by the eigenvectors of the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{v}_i^T\\boldsymbol{A}\\boldsymbol{v}_j= \\lambda\\boldsymbol{v}_i^T\\boldsymbol{v}_j,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is zero unless $i=j$. \n",
+ "\n",
+ "Assume now that we have a symmetric positive-definite matrix $\\boldsymbol{A}$ of size\n",
+ "$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_{i+1}=\\boldsymbol{x}_{i}+\\alpha_i\\boldsymbol{p}_{i}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We assume that $\\boldsymbol{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \n",
+ "Then the $\\boldsymbol{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n",
+ "$ \\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}$ in this basis, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i \\boldsymbol{p}_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The coefficients are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying with $\\boldsymbol{p}_k^T$ from the left gives"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{p}_i= \\boldsymbol{p}_k^T \\boldsymbol{b},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we can define the coefficients $\\alpha_k$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\alpha_k = \\frac{\\boldsymbol{p}_k^T \\boldsymbol{b}}{\\boldsymbol{p}_k^T \\boldsymbol{A} \\boldsymbol{p}_k}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we choose the conjugate vectors $\\boldsymbol{p}_k$ carefully, \n",
+ "then we may not need all of them to obtain a good approximation to the solution \n",
+ "$\\boldsymbol{x}$. \n",
+ "We want to regard the conjugate gradient method as an iterative method. \n",
+ "This will us to solve systems where $n$ is so large that the direct \n",
+ "method would take too much time.\n",
+ "\n",
+ "We denote the initial guess for $\\boldsymbol{x}$ as $\\boldsymbol{x}_0$. \n",
+ "We can assume without loss of generality that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_0=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or consider the system"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "instead.\n",
+ "\n",
+ "One can show that the solution $\\boldsymbol{x}$ is also the unique minimizer of the quadratic form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This suggests taking the first basis vector $\\boldsymbol{p}_1$ \n",
+ "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n",
+ "which equals"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$.\n",
+ "The other vectors in the basis will be conjugate to the gradient, \n",
+ "hence the name conjugate gradient method.\n",
+ "\n",
+ "Let $\\boldsymbol{r}_k$ be the residual at the $k$-th step:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{r}_k=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that $\\boldsymbol{r}_k$ is the negative gradient of $f$ at \n",
+ "$\\boldsymbol{x}=\\boldsymbol{x}_k$, \n",
+ "so the gradient descent method would be to move in the direction $\\boldsymbol{r}_k$. \n",
+ "Here, we insist that the directions $\\boldsymbol{p}_k$ are conjugate to each other, \n",
+ "so we take the direction closest to the gradient $\\boldsymbol{r}_k$ \n",
+ "under the conjugacy constraint. \n",
+ "This gives the following expression"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{p}_{k+1}=\\boldsymbol{r}_k-\\frac{\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{r}_k}{\\boldsymbol{p}_k^T\\boldsymbol{A}\\boldsymbol{p}_k} \\boldsymbol{p}_k.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can also compute the residual iteratively as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which equals"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{p}_k),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{p}_k,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{r}_{k+1}=\\boldsymbol{r}_k-\\boldsymbol{A}\\boldsymbol{p}_{k},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Revisiting our Linear Regression Solvers\n",
+ "\n",
+ "We will use linear regression as a case study for the gradient descent\n",
+ "methods. Linear regression is a great test case for the gradient\n",
+ "descent methods discussed in the lectures since it has several\n",
+ "desirable properties such as:\n",
+ "\n",
+ "1. An analytical solution.\n",
+ "\n",
+ "2. The gradient can be computed analytically.\n",
+ "\n",
+ "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\n",
+ "\n",
+ "We revisit an example similar to what we had in the first homework set. We had a function of the type"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "m = 100\n",
+ "x = 2*np.random.rand(m,1)\n",
+ "y = 4+3*x+np.random.randn(m,1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n",
+ "The linear regression model is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "h_\\beta(x) = \\boldsymbol{y} = \\beta_0 + \\beta_1 x,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "such that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}_i = \\beta_0 + \\beta_1 x_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n",
+ "\n",
+ "It is convenient to write $\\mathbf{\\boldsymbol{y}} = X\\beta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by (we keep the intercept here)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "X \\equiv \\begin{bmatrix}\n",
+ "1 & x_1 \\\\\n",
+ "\\vdots & \\vdots \\\\\n",
+ "1 & x_{100} & \\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The cost/loss/risk function is given by ("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\beta) = \\frac{1}{n}||X\\beta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\\right]\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we want to find $\\beta$ such that $C(\\beta)$ is minimized.\n",
+ "\n",
+ "\n",
+ "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\nabla_{\\beta} C(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n",
+ "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n",
+ "\\end{bmatrix} = \\frac{2}{n}X^T(X\\beta - \\mathbf{y}),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $X$ is the design matrix defined above.\n",
+ "\n",
+ "\n",
+ "The Hessian matrix of $C(\\beta)$ is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n",
+ "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n",
+ "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n",
+ "\\end{bmatrix} = \\frac{2}{n}X^T X.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can use the expression we computed for the gradient and let use a\n",
+ "$\\beta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n",
+ "when $||\\nabla_\\beta C(\\beta_k) || \\leq \\epsilon = 10^{-8}$. **Note that the code below does not include the latter stop criterion**.\n",
+ "\n",
+ "And finally we can compare our solution for $\\beta$ with the analytic result given by \n",
+ "$\\beta= (X^TX)^{-1} X^T \\mathbf{y}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Here is our simple example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "# Importing various packages\n",
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from mpl_toolkits.mplot3d import Axes3D\n",
+ "from matplotlib import cm\n",
+ "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
+ "import sys\n",
+ "\n",
+ "# the number of datapoints\n",
+ "n = 100\n",
+ "x = 2*np.random.rand(n,1)\n",
+ "y = 4+3*x+np.random.randn(n,1)\n",
+ "\n",
+ "X = np.c_[np.ones((n,1)), x]\n",
+ "# Hessian matrix\n",
+ "H = (2.0/n)* X.T @ X\n",
+ "# Get the eigenvalues\n",
+ "EigValues, EigVectors = np.linalg.eig(H)\n",
+ "print(EigValues)\n",
+ "\n",
+ "beta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(beta_linreg)\n",
+ "beta = np.random.randn(2,1)\n",
+ "\n",
+ "eta = 1.0/np.max(EigValues)\n",
+ "Niterations = 1000\n",
+ "\n",
+ "for iter in range(Niterations):\n",
+ " gradient = (2.0/n)*X.T @ (X @ beta-y)\n",
+ " beta -= eta*gradient\n",
+ "\n",
+ "print(beta)\n",
+ "xnew = np.array([[0],[2]])\n",
+ "xbnew = np.c_[np.ones((2,1)), xnew]\n",
+ "ypredict = xbnew.dot(beta)\n",
+ "ypredict2 = xbnew.dot(beta_linreg)\n",
+ "plt.plot(xnew, ypredict, \"r-\")\n",
+ "plt.plot(xnew, ypredict2, \"b-\")\n",
+ "plt.plot(x, y ,'ro')\n",
+ "plt.axis([0,2.0,0, 15.0])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$y$')\n",
+ "plt.title(r'Gradient descent example')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Alternatively, we can use **Scikit-Learn** as done here"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import SGDRegressor\n",
+ "\n",
+ "n = 100\n",
+ "x = 2*np.random.rand(n,1)\n",
+ "y = 4+3*x+np.random.randn(n,1)\n",
+ "\n",
+ "X = np.c_[np.ones((n,1)), x]\n",
+ "beta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n",
+ "print(beta_linreg)\n",
+ "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n",
+ "sgdreg.fit(x,y.ravel())\n",
+ "print(sgdreg.intercept_, sgdreg.coef_)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\beta$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C_{\\text{ridge}}(\\beta) = \\frac{1}{n}||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we only have adjust the gradient as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n",
+ "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n",
+ "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\beta_0 \\\\ \\beta_1\\end{bmatrix} = 2 (X^T(X\\beta - \\mathbf{y})+\\lambda \\beta).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can easily extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_{\\text{ridge}} = \\left(X^T X + \\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from mpl_toolkits.mplot3d import Axes3D\n",
+ "from matplotlib import cm\n",
+ "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
+ "import sys\n",
+ "\n",
+ "# the number of datapoints\n",
+ "n = 100\n",
+ "x = 2*np.random.rand(n,1)\n",
+ "y = 4+3*x+np.random.randn(n,1)\n",
+ "\n",
+ "X = np.c_[np.ones((n,1)), x]\n",
+ "XT_X = X.T @ X\n",
+ "\n",
+ "#Ridge parameter lambda\n",
+ "lmbda = 0.001\n",
+ "Id = lmbda* np.eye(XT_X.shape[0])\n",
+ "\n",
+ "beta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y\n",
+ "print(beta_linreg)\n",
+ "# Start plain gradient descent\n",
+ "beta = np.random.randn(2,1)\n",
+ "\n",
+ "eta = 0.1\n",
+ "Niterations = 100\n",
+ "\n",
+ "for iter in range(Niterations):\n",
+ " gradients = 2.0/n*X.T @ (X @ (beta)-y)+2*lmbda*beta\n",
+ " beta -= eta*gradients\n",
+ "\n",
+ "print(beta)\n",
+ "ypredict = X @ beta\n",
+ "ypredict2 = X @ beta_linreg\n",
+ "plt.plot(x, ypredict, \"r-\")\n",
+ "plt.plot(x, ypredict2, \"b-\")\n",
+ "plt.plot(x, y ,'ro')\n",
+ "plt.axis([0,2.0,0, 15.0])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$y$')\n",
+ "plt.title(r'Gradient descent example for Ridge')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Using gradient descent methods, limitations\n",
+ "\n",
+ "* **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 cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk 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.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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. \n",
+ "\n",
+ "* 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.\n",
+ "\n",
+ "## Stochastic Gradient Descent\n",
+ "\n",
+ "Stochastic gradient descent (SGD) and variants thereof address some of\n",
+ "the shortcomings of the Gradient descent method discussed above.\n",
+ "\n",
+ "The underlying idea of SGD comes from the observation that the cost\n",
+ "function, which we want to minimize, can almost always be written as a\n",
+ "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n",
+ "\\mathbf{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This in turn means that the gradient can be\n",
+ "computed as a sum over $i$-gradients"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n",
+ "\\mathbf{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Stochasticity/randomness is introduced by only taking the\n",
+ "gradient on a subset of the data called minibatches. If there are $n$\n",
+ "data points and the size of each minibatch is $M$, there will be $n/M$\n",
+ "minibatches. We denote these minibatches by $B_k$ where\n",
+ "$k=1,\\cdots,n/M$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n",
+ "and we choose to have $M=5$ minibathces,\n",
+ "then each minibatch contains two data points. In particular we have\n",
+ "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n",
+ "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n",
+ "have only a single batch with all data points and on the other extreme,\n",
+ "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n",
+ "$B_k = \\mathbf{x}_k$.\n",
+ "\n",
+ "The idea is now to approximate the gradient by replacing the sum over\n",
+ "all data points with a sum over the data points in one the minibatches\n",
+ "picked at random in each gradient descent step"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\nabla_{\\beta}\n",
+ "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n",
+ "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n",
+ "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Thus a gradient descent step now looks like"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n",
+ "\\mathbf{\\beta})\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $k$ is picked at random with equal\n",
+ "probability from $[1,n/M]$. An iteration over the number of\n",
+ "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n",
+ "typical to choose a number of epochs and for each epoch iterate over\n",
+ "the number of minibatches, as exemplified in the code below."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np \n",
+ "\n",
+ "n = 100 #100 datapoints \n",
+ "M = 5 #size of each minibatch\n",
+ "m = int(n/M) #number of minibatches\n",
+ "n_epochs = 10 #number of epochs\n",
+ "\n",
+ "j = 0\n",
+ "for epoch in range(1,n_epochs+1):\n",
+ " for i in range(m):\n",
+ " k = np.random.randint(m) #Pick the k-th minibatch at random\n",
+ " #Compute the gradient using the data in minibatch Bk\n",
+ " #Compute new suggestion for \n",
+ " j += 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the gradient only on a subset of the data has two important\n",
+ "benefits. First, it introduces randomness which decreases the chance\n",
+ "that our opmization scheme gets stuck in a local minima. Second, if\n",
+ "the size of the minibatches are small relative to the number of\n",
+ "datapoints ($M < n$), the computation of the gradient is much\n",
+ "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n",
+ "all $n$ datapoints.\n",
+ "\n",
+ "\n",
+ "\n",
+ "A natural question is when do we stop the search for a new minimum?\n",
+ "One possibility is to compute the full gradient after a given number\n",
+ "of epochs and check if the norm of the gradient is smaller than some\n",
+ "threshold and stop if true. However, the condition that the gradient\n",
+ "is zero is valid also for local minima, so this would only tell us\n",
+ "that we are close to a local/global minimum. However, we could also\n",
+ "evaluate the cost function at this point, store the result and\n",
+ "continue the search. If the test kicks in at a later stage we can\n",
+ "compare the values of the cost function and keep the $\\beta$ that\n",
+ "gave the lowest value.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Another approach is to let the step length $\\gamma_j$ depend on the\n",
+ "number of epochs in such a way that it becomes very small after a\n",
+ "reasonable time such that we do not move at all.\n",
+ "\n",
+ "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$.\n",
+ "\n",
+ "In this way we can fix the number of epochs, compute $\\beta$ and\n",
+ "evaluate the cost function at the end. Repeating the computation will\n",
+ "give a different result since the scheme is random by design. Then we\n",
+ "pick the final $\\beta$ that gives the lowest value of the cost\n",
+ "function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np \n",
+ "\n",
+ "def step_length(t,t0,t1):\n",
+ " return t0/(t+t1)\n",
+ "\n",
+ "n = 100 #100 datapoints \n",
+ "M = 5 #size of each minibatch\n",
+ "m = int(n/M) #number of minibatches\n",
+ "n_epochs = 500 #number of epochs\n",
+ "t0 = 1.0\n",
+ "t1 = 10\n",
+ "\n",
+ "gamma_j = t0/t1\n",
+ "j = 0\n",
+ "for epoch in range(1,n_epochs+1):\n",
+ " for i in range(m):\n",
+ " k = np.random.randint(m) #Pick the k-th minibatch at random\n",
+ " #Compute the gradient using the data in minibatch Bk\n",
+ " #Compute new suggestion for beta\n",
+ " t = epoch*m+i\n",
+ " gamma_j = step_length(t,t0,t1)\n",
+ " j += 1\n",
+ "\n",
+ "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Program for stochastic gradient"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "from math import exp, sqrt\n",
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import SGDRegressor\n",
+ "\n",
+ "m = 100\n",
+ "x = 2*np.random.rand(m,1)\n",
+ "y = 4+3*x+np.random.randn(m,1)\n",
+ "\n",
+ "X = np.c_[np.ones((m,1)), x]\n",
+ "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n",
+ "print(\"Own inversion\")\n",
+ "print(theta_linreg)\n",
+ "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n",
+ "sgdreg.fit(x,y.ravel())\n",
+ "print(\"sgdreg from scikit\")\n",
+ "print(sgdreg.intercept_, sgdreg.coef_)\n",
+ "\n",
+ "\n",
+ "theta = np.random.randn(2,1)\n",
+ "eta = 0.1\n",
+ "Niterations = 1000\n",
+ "\n",
+ "\n",
+ "for iter in range(Niterations):\n",
+ " gradients = 2.0/m*X.T @ ((X @ theta)-y)\n",
+ " theta -= eta*gradients\n",
+ "print(\"theta from own gd\")\n",
+ "print(theta)\n",
+ "\n",
+ "xnew = np.array([[0],[2]])\n",
+ "Xnew = np.c_[np.ones((2,1)), xnew]\n",
+ "ypredict = Xnew.dot(theta)\n",
+ "ypredict2 = Xnew.dot(theta_linreg)\n",
+ "\n",
+ "\n",
+ "n_epochs = 50\n",
+ "t0, t1 = 5, 50\n",
+ "def learning_schedule(t):\n",
+ " return t0/(t+t1)\n",
+ "\n",
+ "theta = np.random.randn(2,1)\n",
+ "\n",
+ "for epoch in range(n_epochs):\n",
+ " for i in range(m):\n",
+ " random_index = np.random.randint(m)\n",
+ " xi = X[random_index:random_index+1]\n",
+ " yi = y[random_index:random_index+1]\n",
+ " gradients = 2 * xi.T @ ((xi @ theta)-yi)\n",
+ " eta = learning_schedule(epoch*m+i)\n",
+ " theta = theta - eta*gradients\n",
+ "print(\"theta from own sdg\")\n",
+ "print(theta)\n",
+ "\n",
+ "plt.plot(xnew, ypredict, \"r-\")\n",
+ "plt.plot(xnew, ypredict2, \"b-\")\n",
+ "plt.plot(x, y ,'ro')\n",
+ "plt.axis([0,2.0,0, 15.0])\n",
+ "plt.xlabel(r'$x$')\n",
+ "plt.ylabel(r'$y$')\n",
+ "plt.title(r'Random numbers ')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Momentum based GD\n",
+ "\n",
+ "The stochastic gradient descent (SGD) is almost always used with a\n",
+ "*momentum* or inertia term that serves as a memory of the direction we\n",
+ "are moving in parameter space. This is typically implemented as\n",
+ "follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n",
+ "\\label{_auto1} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have introduced a momentum parameter $\\gamma$, with\n",
+ "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n",
+ "indicate the gradient is to be taken over a different mini-batch at\n",
+ "each step. We call this algorithm gradient descent with momentum\n",
+ "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n",
+ "running average of recently encountered gradients and\n",
+ "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n",
+ "used in the averaging procedure. Consistent with this, when\n",
+ "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n",
+ "earlier. An equivalent way of writing the updates is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us try to get more intuition from these equations. It is helpful\n",
+ "to consider a simple physical analogy with a particle of mass $m$\n",
+ "moving in a viscous medium with drag coefficient $\\mu$ and potential\n",
+ "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n",
+ "then its motion is described by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can discretize this equation in the usual way to get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "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}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Rearranging this equation, we can rewrite this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Notice that this equation is identical to previous one if we identify\n",
+ "the position of the particle, $\\mathbf{w}$, with the parameters\n",
+ "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n",
+ "parameter and learning rate with the mass of the particle and the\n",
+ "viscous drag as:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Thus, as the name suggests, the momentum parameter is proportional to\n",
+ "the mass of the particle and effectively provides inertia.\n",
+ "Furthermore, in the large viscosity/small learning rate limit, our\n",
+ "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n",
+ "\n",
+ "Why is momentum useful? SGD momentum helps the gradient descent\n",
+ "algorithm gain speed in directions with persistent but small gradients\n",
+ "even in the presence of stochasticity, while suppressing oscillations\n",
+ "in high-curvature directions. This becomes especially important in\n",
+ "situations where the landscape is shallow and flat in some directions\n",
+ "and narrow and steep in others. It has been argued that first-order\n",
+ "methods (with appropriate initial conditions) can perform comparable\n",
+ "to more expensive second order methods, especially in the context of\n",
+ "complex deep learning models.\n",
+ "\n",
+ "These beneficial properties of momentum can sometimes become even more\n",
+ "pronounced by using a slight modification of the classical momentum\n",
+ "algorithm called Nesterov Accelerated Gradient (NAG).\n",
+ "\n",
+ "In the NAG algorithm, rather than calculating the gradient at the\n",
+ "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n",
+ "calculates the gradient at the expected value of the parameters given\n",
+ "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n",
+ "\\mathbf{v}_{t-1})$. This yields the NAG update rule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n",
+ "\\label{_auto2} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In stochastic gradient descent, with and without momentum, we still\n",
+ "have to specify a schedule for tuning the learning rates $\\eta_t$\n",
+ "as a function of time. As discussed in the context of Newton's\n",
+ "method, this presents a number of dilemmas. The learning rate is\n",
+ "limited by the steepest direction which can change depending on the\n",
+ "current position in the landscape. To circumvent this problem, ideally\n",
+ "our algorithm would keep track of curvature and take large steps in\n",
+ "shallow, flat directions and small steps in steep, narrow directions.\n",
+ "Second-order methods accomplish this by calculating or approximating\n",
+ "the Hessian and normalizing the learning rate by the\n",
+ "curvature. However, this is very computationally expensive for\n",
+ "extremely large models. Ideally, we would like to be able to\n",
+ "adaptively change the step size to match the landscape without paying\n",
+ "the steep computational price of calculating or approximating\n",
+ "Hessians.\n",
+ "\n",
+ "Recently, a number of methods have been introduced that accomplish\n",
+ "this by tracking not only the gradient, but also the second moment of\n",
+ "the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and\n",
+ "ADAM.\n",
+ "\n",
+ "\n",
+ "### RMS prop\n",
+ "\n",
+ "In RMS prop, in addition to keeping a running average of the first\n",
+ "moment of the gradient, we also keep track of the second moment\n",
+ "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n",
+ "for RMS prop is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n",
+ "\\label{_auto3} \\tag{4}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\beta$ controls the averaging time of the second moment and is\n",
+ "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n",
+ "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n",
+ "small regularization constant to prevent divergences. Multiplication\n",
+ "and division by vectors is understood as an element-wise operation. It\n",
+ "is clear from this formula that the learning rate is reduced in\n",
+ "directions where the norm of the gradient is consistently large. This\n",
+ "greatly speeds up the convergence by allowing us to use a larger\n",
+ "learning rate for flat directions.\n",
+ "\n",
+ "### ADAM optimizer\n",
+ "\n",
+ "A related algorithm is the ADAM optimizer. In ADAM, we keep a running\n",
+ "average of both the first and second moment of the gradient and use\n",
+ "this information to adaptively change the learning rate for different\n",
+ "parameters. In addition to keeping a running average of the first and\n",
+ "second moments of the gradient\n",
+ "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n",
+ "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n",
+ "performs an additional bias correction to account for the fact that we\n",
+ "are estimating the first two moments of the gradient using a running\n",
+ "average (denoted by the hats in the update rule below). The update\n",
+ "rule for ADAM is given by (where multiplication and division are once\n",
+ "again understood to be element-wise operations below)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n",
+ "\\label{_auto4} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ "\\label{_auto5} \\tag{6}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n",
+ "second moment and are typically taken to be $0.9$ and $0.99$\n",
+ "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n",
+ "\n",
+ "Like in RMSprop, the effective step size of a parameter depends on the\n",
+ "magnitude of its gradient squared. To understand this better, let us\n",
+ "rewrite this expression in terms of the variance\n",
+ "$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n",
+ "(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n",
+ "update rule for this parameter is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Practical tips\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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 cost function 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.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "* **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.\n",
+ "\n",
+ "## Automatic differentiation\n",
+ "\n",
+ "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n",
+ "also called algorithmic\n",
+ "differentiation or computational differentiation,is a set of\n",
+ "techniques to numerically evaluate the derivative of a function\n",
+ "specified by a computer program. AD exploits the fact that every\n",
+ "computer program, no matter how complicated, executes a sequence of\n",
+ "elementary arithmetic operations (addition, subtraction,\n",
+ "multiplication, division, etc.) and elementary functions (exp, log,\n",
+ "sin, cos, etc.). By applying the chain rule repeatedly to these\n",
+ "operations, derivatives of arbitrary order can be computed\n",
+ "automatically, accurately to working precision, and using at most a\n",
+ "small constant factor more arithmetic operations than the original\n",
+ "program.\n",
+ "\n",
+ "Automatic differentiation is neither:\n",
+ "\n",
+ "* Symbolic differentiation, nor\n",
+ "\n",
+ "* Numerical differentiation (the method of finite differences).\n",
+ "\n",
+ "Symbolic differentiation can lead to inefficient code and faces the\n",
+ "difficulty of converting a computer program into a single expression,\n",
+ "while numerical differentiation can introduce round-off errors in the\n",
+ "discretization process and cancellation\n",
+ "\n",
+ "\n",
+ "\n",
+ "Python has tools for so-called **automatic differentiation**.\n",
+ "Consider the following example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which has the following derivative"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using **autograd** we have"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "\n",
+ "# To do elementwise differentiation:\n",
+ "from autograd import elementwise_grad as egrad \n",
+ "\n",
+ "# To plot:\n",
+ "import matplotlib.pyplot as plt \n",
+ "\n",
+ "\n",
+ "def f(x):\n",
+ " return np.sin(2*np.pi*x + x**2)\n",
+ "\n",
+ "def f_grad_analytic(x):\n",
+ " return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)\n",
+ "\n",
+ "# Do the comparison:\n",
+ "x = np.linspace(0,1,1000)\n",
+ "\n",
+ "f_grad = egrad(f)\n",
+ "\n",
+ "computed = f_grad(x)\n",
+ "analytic = f_grad_analytic(x)\n",
+ "\n",
+ "plt.title('Derivative computed from Autograd compared with the analytical derivative')\n",
+ "plt.plot(x,computed,label='autograd')\n",
+ "plt.plot(x,analytic,label='analytic')\n",
+ "\n",
+ "plt.xlabel('x')\n",
+ "plt.ylabel('y')\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()\n",
+ "\n",
+ "print(\"The max absolute difference is: %g\"%(np.max(np.abs(computed - analytic))))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we\n",
+ "experiment with what kind of functions Autograd is capable\n",
+ "of finding the gradient of. The following Python functions are just\n",
+ "meant to illustrate what Autograd can do, but please feel free to\n",
+ "experiment with other, possibly more complicated, functions as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "\n",
+ "def f1(x):\n",
+ " return x**3 + 1\n",
+ "\n",
+ "f1_grad = grad(f1)\n",
+ "\n",
+ "# Remember to send in float as argument to the computed gradient from Autograd!\n",
+ "a = 1.0\n",
+ "\n",
+ "# See the evaluated gradient at a using autograd:\n",
+ "print(\"The gradient of f1 evaluated at a = %g using autograd is: %g\"%(a,f1_grad(a)))\n",
+ "\n",
+ "# Compare with the analytical derivative, that is f1'(x) = 3*x**2 \n",
+ "grad_analytical = 3*a**2\n",
+ "print(\"The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g\"%(a,grad_analytical))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To differentiate with respect to two (or more) arguments of a Python\n",
+ "function, Autograd need to know at which variable the function if\n",
+ "being differentiated with respect to."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f2(x1,x2):\n",
+ " return 3*x1**3 + x2*(x1 - 5) + 1\n",
+ "\n",
+ "# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1\n",
+ "f2_grad_x1 = grad(f2,0)\n",
+ "\n",
+ "# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad\n",
+ "f2_grad_x2 = grad(f2,1)\n",
+ "\n",
+ "x1 = 1.0\n",
+ "x2 = 3.0 \n",
+ "\n",
+ "print(\"Evaluating at x1 = %g, x2 = %g\"%(x1,x2))\n",
+ "print(\"-\"*30)\n",
+ "\n",
+ "# Compare with the analytical derivatives:\n",
+ "\n",
+ "# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:\n",
+ "f2_grad_x1_analytical = 9*x1**2 + x2\n",
+ "\n",
+ "# Derivative of f2 w.r.t x2 is: x1 - 5:\n",
+ "f2_grad_x2_analytical = x1 - 5\n",
+ "\n",
+ "# See the evaluated derivations:\n",
+ "print(\"The derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n",
+ "print(\"The analytical derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n",
+ "\n",
+ "print()\n",
+ "\n",
+ "print(\"The derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))\n",
+ "print(\"The analytical derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f3(x): # Assumes x is an array of length 5 or higher\n",
+ " return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2\n",
+ "\n",
+ "f3_grad = grad(f3)\n",
+ "\n",
+ "x = np.linspace(0,4,5)\n",
+ "\n",
+ "# Print the computed gradient:\n",
+ "print(\"The computed gradient of f3 is: \", f3_grad(x))\n",
+ "\n",
+ "# The analytical gradient is: (2, 3, 5, 7, 22*x[4])\n",
+ "f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])\n",
+ "\n",
+ "# Print the analytical gradient:\n",
+ "print(\"The analytical gradient of f3 is: \", f3_grad_analytical)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that in this case, when sending an array as input argument, the\n",
+ "output from Autograd is another array. This is the true gradient of\n",
+ "the function, as opposed to the function in the previous example. By\n",
+ "using arrays to represent the variables, the output from Autograd\n",
+ "might be easier to work with, as the output is closer to what one\n",
+ "could expect form a gradient-evaluting function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f4(x):\n",
+ " return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)\n",
+ "\n",
+ "f4_grad = grad(f4)\n",
+ "\n",
+ "x = 2.7\n",
+ "\n",
+ "# Print the computed derivative:\n",
+ "print(\"The computed derivative of f4 at x = %g is: %g\"%(x,f4_grad(x)))\n",
+ "\n",
+ "# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi\n",
+ "f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi\n",
+ "\n",
+ "# Print the analytical gradient:\n",
+ "print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f5(x):\n",
+ " if x >= 0:\n",
+ " return x**2\n",
+ " else:\n",
+ " return -3*x + 1\n",
+ "\n",
+ "f5_grad = grad(f5)\n",
+ "\n",
+ "x = 2.7\n",
+ "\n",
+ "# Print the computed derivative:\n",
+ "print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "1\n",
+ "8\n",
+ " \n",
+ "<\n",
+ "<\n",
+ "<\n",
+ "!\n",
+ "!\n",
+ "C\n",
+ "O\n",
+ "D\n",
+ "E\n",
+ "_\n",
+ "B\n",
+ "L\n",
+ "O\n",
+ "C\n",
+ "K\n",
+ " \n",
+ " \n",
+ "p\n",
+ "y\n",
+ "c\n",
+ "o\n",
+ "d"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9\n",
+ "# The analytical derivative is: sum(i*x**(i-1)) \n",
+ "f6_grad_analytical = 0\n",
+ "for i in range(10):\n",
+ " f6_grad_analytical += i*x**(i-1)\n",
+ "\n",
+ "print(\"The analytical derivative of f6 at x = %g is: %g\"%(x,f6_grad_analytical))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "\n",
+ "def f7(n): # Assume that n is an integer\n",
+ " if n == 1 or n == 0:\n",
+ " return 1\n",
+ " else:\n",
+ " return n*f7(n-1)\n",
+ "\n",
+ "f7_grad = grad(f7)\n",
+ "\n",
+ "n = 2.0\n",
+ "\n",
+ "print(\"The computed derivative of f7 at n = %d is: %g\"%(n,f7_grad(n)))\n",
+ "\n",
+ "# The function f7 is an implementation of the factorial of n.\n",
+ "# By using the product rule, one can find that the derivative is:\n",
+ "\n",
+ "f7_grad_analytical = 0\n",
+ "for i in range(int(n)-1):\n",
+ " tmp = 1\n",
+ " for k in range(int(n)-1):\n",
+ " if k != i:\n",
+ " tmp *= (n - k)\n",
+ " f7_grad_analytical += tmp\n",
+ "\n",
+ "print(\"The analytical derivative of f7 at n = %d is: %g\"%(n,f7_grad_analytical))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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.\n",
+ "\n",
+ "\n",
+ "Autograd supports many features. However, there are some functions that are not supported (yet) by Autograd.\n",
+ "\n",
+ "Assigning a value to the variable being differentiated with respect to is an example thereof."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "#import autograd.numpy as np\n",
+ "#from autograd import grad\n",
+ "#def f8(x): # Assume x is an array\n",
+ "# x[2] = 3\n",
+ "# return x*2\n",
+ "\n",
+ "#f8_grad = grad(f8)\n",
+ "\n",
+ "#x = 8.4\n",
+ "\n",
+ "#print(\"The derivative of f8 is:\",f8_grad(x))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f9(a): # Assume a is an array with 2 elements\n",
+ " b = np.array([1.0,2.0])\n",
+ " return a.dot(b)\n",
+ "\n",
+ "f9_grad = grad(f9)\n",
+ "\n",
+ "x = np.array([1.0,0.0])\n",
+ "\n",
+ "print(\"The derivative of f9 is:\",f9_grad(x))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we are told that the 'dot' function does not belong to Autograd's\n",
+ "version of a Numpy array. To overcome this, an alternative syntax\n",
+ "which also computed the dot product can be used:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import autograd.numpy as np\n",
+ "from autograd import grad\n",
+ "def f9_alternative(x): # Assume a is an array with 2 elements\n",
+ " b = np.array([1.0,2.0])\n",
+ " return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2\n",
+ "\n",
+ "f9_alternative_grad = grad(f9_alternative)\n",
+ "\n",
+ "x = np.array([3.0,0.0])\n",
+ "\n",
+ "print(\"The gradient of f9 is:\",f9_alternative_grad(x))\n",
+ "\n",
+ "# 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\n",
+ "# w.r.t x is (b_1, b_2)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The documentation recommends to avoid inplace operations such as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "a += b\n",
+ "a -= b\n",
+ "a*= b\n",
+ "a /=b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "More examples will be added, in particular how to compare autograd with own codes for the gradients."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/intro.md b/doc/LectureNotes/_build/html/_sources/intro.md
new file mode 100644
index 000000000..95698c010
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/intro.md
@@ -0,0 +1,141 @@
+# Applied Data Analysis and Machine Learning, FYS-STK3155/4155 at the University of Oslo, Norway
+
+## Introduction
+
+Probability theory and statistical methods play a central role in Science. Nowadays we are
+surrounded by huge amounts of data. For example, there are more than one trillion web pages; more than one
+hour of video is uploaded to YouTube every second, amounting to years of content every
+day; the genomes of 1000s of people, each of which has a length of more than a billion base pairs, have
+been sequenced by various labs and so on. This deluge of data calls for automated methods of data analysis,
+which is exactly what machine learning aims at providing.
+
+## Learning outcomes
+
+This course aims at giving you insights and knowledge about many of the central algorithms used in Data Analysis and Machine Learning. The course is project based and through various numerical projects and weekly exercises you will be exposed to fundamental research problems in these fields, with the aim to reproduce state of the art scientific results. Both supervised and unsupervised methods will be covered. The emphasis is on a frequentist approach with an emphasis on predictions and correaltions. However, we will try, where appropriate, to link our machine learning models with a Bayesian approach as well. You will learn to develop and structure large codes for studying different cases where Machine Learning is applied to, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. More specifically, after this course you will
+
+- Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;
+- Be capable of extending the acquired knowledge to other systems and cases;
+- Have an understanding of central algorithms used in data analysis and machine learning;
+- Understand linear methods for regression and classification, from ordinary least squares, via Lasso and Ridge to Logistic regression and Kernel regression;
+- Learn about neural networks and deep learning methods for supervised and unsupervised learning. Emphasis on feed forward neural networks, convolutional and recurrent neural networks;
+- Learn about about decision trees, random forests, bagging and boosting methods;
+- Learn about support vector machines and kernel transformations;
+- Reduction of data sets and unsupervised learning, from PCA to clustering;
+- Autoencoders and Reinforcement Learning;
+- Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++ and/or Fortran (Fortran2003 or later).
+
+## Prerequisites and background
+
+Basic knowledge in programming and mathematics, with an emphasis on linear algebra. Knowledge of Python or/and C++ as programming languages is strongly recommended and experience with Jupyter notebooks is recommended. Required courses are the equivalents to the University of Oslo mathematics courses MAT1100, MAT1110, MAT1120 and at least one of the corresponding computing and programming courses INF1000/INF1110 or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities offer nowadays a basic programming course (often compulsory) where Python is the recurring programming language.
+We recommend also refreshing your knowledge on Statistics and Probability theory. The lecture notes at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/intro.html offer a review of Statistics and Probability theory.
+
+## The course has two central parts
+
+1. Statistical analysis and optimization of data
+2. Machine learning
+
+
+### Statistical analysis and optimization of data
+
+The following topics will be covered
+- Basic concepts, expectation values, variance, covariance, correlation functions and errors;
+- Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
+- Central elements of Bayesian statistics and modeling;
+- Gradient methods for data optimization,
+- Monte Carlo methods, Markov chains, Gibbs sampling and Metropolis-Hastings sampling;
+- Estimation of errors and resampling techniques such as the cross-validation, blocking, bootstrapping and jackknife methods;
+- Principal Component Analysis (PCA) and its mathematical foundation
+
+### Machine learning
+
+The following topics will be covered:
+- Linear Regression and Logistic Regression;
+- Neural networks and deep learning, including convolutional and recurrent neural networks
+- Decisions trees, Random Forests, Bagging and Boosting
+- Support vector machines
+- Bayesian linear and logistic regression
+- Boltzmann Machines
+- Unsupervised learning Dimensionality reduction, PCA, k-means and clustering
+- Autoenconders
+
+Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.
+
+Computational aspects play a central role and you are
+expected to work on numerical examples and projects which illustrate
+the theory and various algorithms discussed during the lectures. We recommend strongly to form small project groups of 2-3 participants, if possible.
+
+
+
+## Required Technologies
+
+Course participants are expected to have their own laptops/PCs. We use _Git_ as version control software and the usage of providers like _GitHub_, _GitLab_ or similar are strongly recommended. If you are not familiar with Git as version control software, the following video may be of interest, see https://www.youtube.com/watch?v=RGOj5yH7evk&ab_channel=freeCodeCamp.org
+
+We will make extensive use of Python as programming language and its
+myriad of available libraries. You will find
+Jupyter notebooks invaluable in your work. You can run _R_
+codes in the Jupyter/IPython notebooks, with the immediate benefit of
+visualizing your data. You can also use compiled languages like C++,
+Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be
+on Python.
+
+
+If you have Python installed and you feel
+pretty familiar with installing different packages, we recommend that
+you install the following Python packages via _pip_ as
+
+* pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
+
+For OSX users we recommend, after having installed Xcode, to
+install _brew_. Brew allows for a seamless installation of additional
+software via for example
+
+* brew install python3
+
+For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
+you can use _pip_ as well and simply install Python as
+
+* sudo apt-get install python3
+
+### Python installers
+
+If you don't want to perform these operations separately and venture
+into the hassle of exploring how to set up dependencies and paths, we
+recommend two widely used distrubutions which set up all relevant
+dependencies for Python, namely
+
+* Anaconda:https://docs.anaconda.com/,
+
+which is an open source
+distribution of the Python and R programming languages for large-scale
+data processing, predictive analytics, and scientific computing, that
+aims to simplify package management and deployment. Package versions
+are managed by the package management system _conda_.
+
+* Enthought canopy:https://www.enthought.com/product/canopy/
+
+is a Python
+distribution for scientific and analytic computing distribution and
+analysis environment, available for free and under a commercial
+license.
+
+Furthermore, Google's Colab:https://colab.research.google.com/notebooks/welcome.ipynb is a free Jupyter notebook environment that requires
+no setup and runs entirely in the cloud. Try it out!
+
+### Useful Python libraries
+Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)
+
+* _NumPy_:https://www.numpy.org/ is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
+* _The pandas_:https://pandas.pydata.org/ library provides high-performance, easy-to-use data structures and data analysis tools
+* _Xarray_:http://xarray.pydata.org/en/stable/ is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!
+* _Scipy_:https://www.scipy.org/ (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.
+* _Matplotlib_:https://matplotlib.org/ is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
+* _Autograd_:https://github.com/HIPS/autograd can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives
+* _SymPy_:https://www.sympy.org/en/index.html is a Python library for symbolic mathematics.
+* _scikit-learn_:https://scikit-learn.org/stable/ has simple and efficient tools for machine learning, data mining and data analysis
+* _TensorFlow_:https://www.tensorflow.org/ is a Python library for fast numerical computing created and released by Google
+* _Keras_:https://keras.io/ is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
+* And many more such as _pytorch_:https://pytorch.org/, _Theano_:https://pypi.org/project/Theano/ etc
+
+
+
+
diff --git a/doc/LectureNotes/_build/html/_sources/linalg.ipynb b/doc/LectureNotes/_build/html/_sources/linalg.ipynb
new file mode 100644
index 000000000..e915954aa
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/linalg.ipynb
@@ -0,0 +1,1494 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Linear Algebra, Handling of Arrays and more Python Features\n",
+ "\n",
+ "## Introduction\n",
+ "\n",
+ "The aim of this set of lectures is to review some central linear algebra algorithms that we will need in our \n",
+ "data analysis part and in the construction of Machine Learning algorithms (ML). \n",
+ "This will allow us to introduce some central programming features of high-level languages like Python and \n",
+ "compiled languages like C++ and/or Fortran. \n",
+ "\n",
+ "As discussed in the introductory notes, these series of lectures focuses both on using\n",
+ "central Python packages like **tensorflow** and **scikit-learn** as well\n",
+ "as writing your own codes for some central ML algorithms. The\n",
+ "latter can be written in a language of your choice, be it Python, Julia, R,\n",
+ "Rust, C++, Fortran etc. In order to avoid confusion however, in these lectures we will limit our\n",
+ "attention to Python, C++ and Fortran. \n",
+ "\n",
+ "\n",
+ "## Important Matrix and vector handling packages\n",
+ "\n",
+ "There are several central software packages for linear algebra and eigenvalue problems. Several of the more\n",
+ "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n",
+ "software package LAPACK, which follows two other popular packages\n",
+ "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n",
+ "\n",
+ " * LINPACK: package for linear equations and least square problems.\n",
+ "\n",
+ " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n",
+ "\n",
+ " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n",
+ "\n",
+ "When dealing with matrices and vectors a central issue is memory\n",
+ "handling and allocation. If our code is written in Python the way we\n",
+ "declare these objects and the way they are handled, interpreted and\n",
+ "used by say a linear algebra library, requires codes that interface\n",
+ "our Python program with such libraries. For Python programmers,\n",
+ "**Numpy** is by now the standard Python package for numerical arrays in\n",
+ "Python as well as the source of functions which act on these\n",
+ "arrays. These functions span from eigenvalue solvers to functions that\n",
+ "compute the mean value, variance or the covariance matrix. If you are\n",
+ "not familiar with how arrays are handled in say Python or compiled\n",
+ "languages like C++ and Fortran, the sections in this chapter may be\n",
+ "useful. For C++ programmer, **Armadillo** is widely used library for\n",
+ "linear algebra and eigenvalue problems. In addition it offers a\n",
+ "convenient way to handle and organize arrays. We discuss this library\n",
+ "as well. Before we proceed we believe it may be convenient to repeat some basic features of \n",
+ " matrices and vectors.\n",
+ "\n",
+ "\n",
+ "## Basic Matrix Features\n",
+ "\n",
+ "Matrix properties reminder"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A} =\n",
+ " \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n",
+ " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n",
+ " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n",
+ " a_{41} & a_{42} & a_{43} & a_{44}\n",
+ " \\end{bmatrix}\\qquad\n",
+ "\\mathbf{I} =\n",
+ " \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n",
+ " 0 & 1 & 0 & 0 \\\\\n",
+ " 0 & 0 & 1 & 0 \\\\\n",
+ " 0 & 0 & 0 & 1\n",
+ " \\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The inverse of a matrix is defined by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "
\n",
+ "### Some famous Matrices\n",
+ "\n",
+ " * Diagonal if $a_{ij}=0$ for $i\\ne j$\n",
+ "\n",
+ " * Upper triangular if $a_{ij}=0$ for $i > j$\n",
+ "\n",
+ " * Lower triangular if $a_{ij}=0$ for $i < j$\n",
+ "\n",
+ " * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n",
+ "\n",
+ " * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n",
+ "\n",
+ " * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n",
+ "\n",
+ " * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n",
+ "\n",
+ " * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n",
+ "\n",
+ " * Banded, block upper triangular, block lower triangular....\n",
+ "\n",
+ "Some Equivalent Statements. For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n",
+ "\n",
+ " * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n",
+ "\n",
+ " * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n",
+ "\n",
+ " * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n",
+ "\n",
+ " * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n",
+ "\n",
+ " * $\\mathbf{A}$ is a product of elementary matrices.\n",
+ "\n",
+ " * $0$ is not eigenvalue of $\\mathbf{A}$.\n",
+ "\n",
+ "## Numpy and arrays\n",
+ "[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we have defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n",
+ "Another alternative is to declare a vector as follows"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "x = np.array([1, 2, 3])\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n",
+ "start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "x = np.log(np.array([4, 7, 8]))\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we have used Numpy's unary function $np.log$. This function is\n",
+ "highly tuned to compute array elements since the code is vectorized\n",
+ "and does not require looping. We normaly recommend that you use the\n",
+ "Numpy intrinsic functions instead of the corresponding **log** function\n",
+ "from Python's **math** module. The looping is done explicitely by the\n",
+ "**np.log** function. The alternative, and slower way to compute the\n",
+ "logarithms of a vector would be to write"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "from math import log\n",
+ "x = np.array([4, 7, 8])\n",
+ "for i in range(0, len(x)):\n",
+ " x[i] = log(x[i])\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note that our code is much longer already and we need to import the **log** function from the **math** module. \n",
+ "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automacally our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "x = np.log(np.array([4, 7, 8], dtype = np.float64))\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "x = np.log(np.array([4.0, 7.0, 8.0])\n",
+ "print(x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "x = np.log(np.array([4.0, 7.0, 8.0])\n",
+ "print(x.itemsize)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Having defined vectors, we are now ready to try out matrices. We can define a $3 \\times 3 $ real matrix $\\hat{A}$\n",
+ "as (recall that we user lowercase letters for vectors and uppercase letters for matrices)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
+ "print(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
+ "# print the first column, row-major order and elements start with 0\n",
+ "print(A[:,0])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can continue this was by printing out other columns or rows. The example here prints out the second column"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
+ "# print the first column, row-major order and elements start with 0\n",
+ "print(A[1,:])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 10\n",
+ "# define a matrix of dimension 10 x 10 and set all elements to zero\n",
+ "A = np.zeros( (n, n) )\n",
+ "print(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or initializing all elements to"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 10\n",
+ "# define a matrix of dimension 10 x 10 and set all elements to one\n",
+ "A = np.ones( (n, n) )\n",
+ "print(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or as unitarily distributed random numbers (see the material on random number generators in the statistics part)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 10\n",
+ "# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n",
+ "A = np.random.rand(n, n)\n",
+ "print(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\n",
+ "As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n",
+ "$\\hat{x}, \\hat{y}, \\hat{z}$ with $n$ elements each. The covariance matrix is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n",
+ " \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n",
+ " \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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. For a more in-depth discussion of the covariance and covariance matrix and its meaning, we refer you to the lectures on statistics. \n",
+ "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $ 3\\times n$ matrix $\\hat{W}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n",
+ " x_1 & y_1 & z_1 \\\\\n",
+ " x_2 & y_2 & z_2 \\\\\n",
+ " \\dots & \\dots & \\dots \\\\\n",
+ " x_{n-2} & y_{n-2} & z_{n-2} \\\\\n",
+ " x_{n-1} & y_{n-1} & z_{n-1}\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $3 times 3$ covariance matrix\n",
+ "$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. In our review of\n",
+ "statistical functions and quantities we will discuss more about the\n",
+ "meaning of the covariance matrix. Here we note that we can calculate\n",
+ "the mean value of each set of samples $\\hat{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "z = x**3+np.random.normal(size=n)\n",
+ "print(np.mean(z))\n",
+ "W = np.vstack((x, y, z))\n",
+ "Sigma = np.cov(W)\n",
+ "print(Sigma)\n",
+ "Eigvals, Eigvecs = np.linalg.eig(Sigma)\n",
+ "print(Eigvals)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from scipy import sparse\n",
+ "eye = np.eye(4)\n",
+ "print(eye)\n",
+ "sparse_mtx = sparse.csr_matrix(eye)\n",
+ "print(sparse_mtx)\n",
+ "x = np.linspace(-10,10,100)\n",
+ "y = np.sin(x)\n",
+ "plt.plot(x,y,marker='x')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other Matrix and Vector Operations\n",
+ "\n",
+ "The following examples show how to compute various quantities like the **mean** value of a matrix or a vector and how to use functions like **reshape** and **ravel**. These are all useful quantities when scaling the data and preparing the data for various machine learning algorithms and when calculating quantities like the mean squared error or the variance."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "Simple code that tests various numpy functions\n",
+ "\"\"\"\n",
+ "\n",
+ "import numpy as np\n",
+ "# Simple test-matrix of dim 3 x 4\n",
+ "a = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9],[10, 11, 12]],dtype=np.float64)\n",
+ "print(f\"The test matrix:{a}\")\n",
+ "# This is the total mean summed over all elements, which here has to be 6.5\n",
+ "print(f\"This is the total mean summed over all elements:{np.mean(a,dtype=np.float64)}\")\n",
+ "# This is the mean for each column, it returns an array with the mean values for each column. It returns a row-like vector\n",
+ "print(f\"This is the mean for each column:{np.mean(a, axis=0, keepdims=True,dtype=np.float64)}\")\n",
+ "# This is the mean value for each row, it returns an array via the keepdims option which is a column-like vector if\n",
+ "# keepdims=True. Else it return a row-like vector\n",
+ "# Try setting keepdims=False\n",
+ "print(f\"This is the mean value for each row:{np.mean(a, axis=1, keepdims=True,dtype=np.float64)}\")\n",
+ "# We print then the mean value for each row by setting keepdims=False\n",
+ "print(f\"This is the mean value for each row with keepdims false:{np.mean(a, axis=1, keepdims=False,dtype=np.float64)}\")\n",
+ "\n",
+ "# Ravel return a contiguous flattened array.\n",
+ "print(f\"Flatten the matrix:{np.ravel(a)}\")\n",
+ "# It is the same as reshaping the matrix into a one-dimensional array\n",
+ "print(f\"Reshape the matrix to a one-dim array:{a.reshape(-1)}\")\n",
+ "# ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest.\n",
+ "# ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest \n",
+ "print(np.ravel(a, order='F'))\n",
+ "# When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering\n",
+ "# ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.\n",
+ "# ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.\n",
+ "# Transposing it\n",
+ "print(np.ravel(a.T))\n",
+ "print(np.ravel(a.T, order='A'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Gaussian Elimination\n",
+ "\n",
+ "We start with the linear set of equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A}\\mathbf{x} = \\mathbf{w}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We assume also that the matrix $\\mathbf{A}$ is non-singular and that the\n",
+ "matrix elements along the diagonal satisfy $a_{ii} \\ne 0$. Simple $4\\times 4 $ example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{bmatrix}\n",
+ " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n",
+ " a_{21}& a_{22} &a_{23}& a_{24}\\\\\n",
+ " a_{31}& a_{32} &a_{33}& a_{34}\\\\\n",
+ " a_{41}& a_{42} &a_{43}& a_{44}\\\\\n",
+ " \\end{bmatrix} \\begin{bmatrix}\n",
+ " x_1\\\\\n",
+ " x_2\\\\\n",
+ " x_3 \\\\\n",
+ " x_4 \\\\\n",
+ " \\end{bmatrix}\n",
+ " =\\begin{bmatrix}\n",
+ " w_1\\\\\n",
+ " w_2\\\\\n",
+ " w_3 \\\\\n",
+ " w_4\\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$\n",
+ "from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown\n",
+ "$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations\n",
+ "we obtain a so-called upper triangular set of equations of the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b_{22}x_2 + b_{23}x_3 + b_{24}x_4=y_2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b_{33}x_3 + b_{34}x_4=y_3 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "b_{44}x_4=y_4. \\nonumber\n",
+ "\\label{eq:gaussbacksub} \\tag{1}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with\n",
+ "what is called a backward substitution. \n",
+ "\n",
+ "\n",
+ "This process can be expressed mathematically as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " x_m = \\frac{1}{b_{mm}}\\left(y_m-\\sum_{k=m+1}^nb_{mk}x_k\\right)\\quad m=n-1,n-2,\\dots,1.\n",
+ "\\label{_auto1} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To arrive at such an upper triangular system of equations, we start by eliminating\n",
+ "the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract\n",
+ "the result from the $j$th equation. We assume obviously that $a_{11}\\ne 0$ and that\n",
+ "$\\mathbf{A}$ is not singular.\n",
+ "\n",
+ "\n",
+ "Our actual $4\\times 4$ example reads after the first operation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{bmatrix}\n",
+ " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n",
+ " 0& (a_{22}-\\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\\frac{a_{21}a_{14}}{a_{11}})\\\\\n",
+ "0& (a_{32}-\\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\\frac{a_{31}a_{14}}{a_{11}})\\\\\n",
+ "0&(a_{42}-\\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\\frac{a_{41}a_{14}}{a_{11}}) \\\\\n",
+ " \\end{bmatrix} \\begin{bmatrix}\n",
+ " x_1\\\\\n",
+ " x_2\\\\\n",
+ " x_3 \\\\\n",
+ " x_4 \\\\\n",
+ " \\end{bmatrix} \n",
+ " =\\begin{bmatrix}\n",
+ " y_1\\\\\n",
+ " w_2^{(2)}\\\\\n",
+ " w_3^{(2)} \\\\\n",
+ " w_4^{(2)}\\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=w^{(2)}_2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=w^{(2)}_3 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=w^{(2)}_4, \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ "\\label{_auto2} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The new coefficients are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " b_{1k} = a_{1k}^{(1)} \\quad k=1,\\dots,n,\n",
+ "\\label{_auto3} \\tag{4}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "a_{jk}^{(2)} = a_{jk}^{(1)}-\\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \\quad j,k=2,\\dots,n,\n",
+ "\\label{_auto4} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a new right-hand side given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "y_{1}=w_1^{(1)}, \\quad w_j^{(2)} =w_j^{(1)}-\\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \\quad j=2,\\dots,n.\n",
+ "\\label{_auto5} \\tag{6}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have also set $w_1^{(1)}=w_1$, the original vector element.\n",
+ "We see that the system of unknowns $x_1,\\dots,x_n$ is transformed into an $(n-1)\\times (n-1)$ problem.\n",
+ "\n",
+ "\n",
+ "\n",
+ "This step is called forward substitution.\n",
+ "Proceeding with these substitutions, we obtain the\n",
+ "general expressions for the new coefficients"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " a_{jk}^{(m+1)} = a_{jk}^{(m)}-\\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \\quad j,k=m+1,\\dots,n,\n",
+ "\\label{_auto6} \\tag{7}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $m=1,\\dots,n-1$ and a\n",
+ "right-hand side given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " w_j^{(m+1)} =w_j^{(m)}-\\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\\quad j=m+1,\\dots,n.\n",
+ "\\label{_auto7} \\tag{8}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This set of $n-1$ elimations leads us to an equations which is solved by back substitution.\n",
+ "If the arithmetics is exact and the matrix $\\mathbf{A}$ is not singular, then the computed answer will be exact.\n",
+ "\n",
+ "Even though the matrix elements along the diagonal are not zero,\n",
+ "numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added\n",
+ "to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$\n",
+ "results in $-10^{-7}$ and that $a_{22}$ is one.\n",
+ "one. We are then\n",
+ "adding $10^7+1$. With single precision this results in $10^7$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ " * Gaussian elimination, $O(2/3n^3)$ flops, general matrix\n",
+ "\n",
+ " * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops\n",
+ "\n",
+ " * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops.\n",
+ "\n",
+ " * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices.\n",
+ "\n",
+ " * Singular value decomposition\n",
+ "\n",
+ " * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops.\n",
+ "\n",
+ "The LU decomposition method means that we can rewrite\n",
+ "this matrix as the product of two matrices $\\mathbf{L}$ and $\\mathbf{U}$\n",
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{bmatrix}\n",
+ " a_{11} & a_{12} & a_{13} & a_{14} \\\\\n",
+ " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n",
+ " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n",
+ " a_{41} & a_{42} & a_{43} & a_{44}\n",
+ " \\end{bmatrix}\n",
+ " = \\begin{bmatrix}\n",
+ " 1 & 0 & 0 & 0 \\\\\n",
+ " l_{21} & 1 & 0 & 0 \\\\\n",
+ " l_{31} & l_{32} & 1 & 0 \\\\\n",
+ " l_{41} & l_{42} & l_{43} & 1\n",
+ " \\end{bmatrix}\n",
+ " \\begin{bmatrix}\n",
+ " u_{11} & u_{12} & u_{13} & u_{14} \\\\\n",
+ " 0 & u_{22} & u_{23} & u_{24} \\\\\n",
+ " 0 & 0 & u_{33} & u_{34} \\\\\n",
+ " 0 & 0 & 0 & u_{44}\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "LU decomposition forms the backbone of other algorithms in linear algebra, such as the\n",
+ "solution of linear equations given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The above set of equations is conveniently solved by using LU decomposition as an intermediate step.\n",
+ "\n",
+ "The matrix $\\mathbf{A}\\in \\mathbb{R}^{n\\times n}$ has an LU factorization if the determinant\n",
+ "is different from zero. If the LU factorization exists and $\\mathbf{A}$ is non-singular, then the LU factorization\n",
+ "is unique and the determinant is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "det\\{\\mathbf{A}\\}=det\\{\\mathbf{LU}\\}= det\\{\\mathbf{L}\\}det\\{\\mathbf{U}\\}=u_{11}u_{22}\\dots u_{nn}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There are at least three main advantages with LU decomposition compared with standard Gaussian elimination:\n",
+ "\n",
+ " * It is straightforward to compute the determinant of a matrix\n",
+ "\n",
+ " * If we have to solve sets of linear equations with the same matrix but with different vectors $\\mathbf{y}$, the number of FLOPS is of the order $n^3$.\n",
+ "\n",
+ " * The inverse is such an operation \n",
+ "\n",
+ "With the LU decomposition it is rather\n",
+ "simple to solve a system of linear equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This can be written in matrix form as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{Ax}=\\mathbf{w}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\mathbf{A}$ and $\\mathbf{w}$ are known and we have to solve for\n",
+ "$\\mathbf{x}$. Using the LU dcomposition we write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A} \\mathbf{x} \\equiv \\mathbf{L} \\mathbf{U} \\mathbf{x} =\\mathbf{w}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The previous equation can be calculated in two steps"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{L} \\mathbf{y} = \\mathbf{w};\\qquad \\mathbf{Ux}=\\mathbf{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To show that this is correct we use to the LU decomposition\n",
+ "to rewrite our system of linear equations as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{LUx}=\\mathbf{w},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and since the determinant of $\\mathbf{L}$ is equal to 1 (by construction\n",
+ "since the diagonals of $\\mathbf{L}$ equal 1) we can use the inverse of\n",
+ "$\\mathbf{L}$ to obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{Ux}=\\mathbf{L^{-1}w}=\\mathbf{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yields the intermediate step"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{L^{-1}w}=\\mathbf{y}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and as soon as we have $\\mathbf{y}$ we can obtain $\\mathbf{x}$\n",
+ "through $\\mathbf{Ux}=\\mathbf{y}$.\n",
+ "\n",
+ "\n",
+ "For our four-dimentional example this takes the form"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "y_1=w_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "l_{21}y_1 + y_2=w_2\\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "l_{31}y_1 + l_{32}y_2 + y_3 =w_3\\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=w_4. \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=y_1 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "u_{22}x_2 + u_{23}x_3 + u_{24}x_4=y_2\\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "u_{33}x_3 + u_{34}x_4=y_3\\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "u_{44}x_4=y_4 \\nonumber\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This example shows the basis for the algorithm\n",
+ "needed to solve the set of $n$ linear equations.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The algorithm goes as follows\n",
+ "\n",
+ " * Set up the matrix $\\bf A$ and the vector $\\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\\bf x$.\n",
+ "\n",
+ " * Then LU decompose the matrix $\\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned.\n",
+ "\n",
+ " * Thereafter you call the function `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\\bf A$ and the vector $\\bf w$ and returns $\\bf x$ in the same place as $\\bf w$. Upon exit the original content in $\\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function.\n",
+ "\n",
+ "### LU Decomposition, the inverse of a matrix\n",
+ "\n",
+ "If the inverse exists then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A}^{-1}\\mathbf{A}=\\mathbf{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "the identity matrix. With an LU decomposed matrix we can rewrite the last equation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{LU}\\mathbf{A}^{-1}=\\mathbf{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we assume that the first column (that is column 1) of the inverse matrix\n",
+ "can be written as a vector with unknown entries"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{A}_1^{-1}= \\begin{bmatrix}\n",
+ " a_{11}^{-1} \\\\\n",
+ " a_{21}^{-1} \\\\\n",
+ " \\dots \\\\\n",
+ " a_{n1}^{-1} \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "then we have a linear set of equations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{LU}\\begin{bmatrix}\n",
+ " a_{11}^{-1} \\\\\n",
+ " a_{21}^{-1} \\\\\n",
+ " \\dots \\\\\n",
+ " a_{n1}^{-1} \\\\\n",
+ " \\end{bmatrix} =\\begin{bmatrix}\n",
+ " 1 \\\\\n",
+ " 0 \\\\\n",
+ " \\dots \\\\\n",
+ " 0 \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In a similar way we can compute the unknow entries of the second column,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbf{LU}\\begin{bmatrix}\n",
+ " a_{12}^{-1} \\\\\n",
+ " a_{22}^{-1} \\\\\n",
+ " \\dots \\\\\n",
+ " a_{n2}^{-1} \\\\\n",
+ " \\end{bmatrix}=\\begin{bmatrix}\n",
+ " 0 \\\\\n",
+ " 1 \\\\\n",
+ " \\dots \\\\\n",
+ " 0 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and continue till we have solved all $n$ sets of linear equations."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/LectureNotes/_build/html/_sources/schedule.md b/doc/LectureNotes/_build/html/_sources/schedule.md
new file mode 100644
index 000000000..5bc748484
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/schedule.md
@@ -0,0 +1,185 @@
+# Teaching schedule with links to material
+
+
+This course will be delivered in a hybrid mode, with online lectures and on site or online laboratory sessions.
+
+1. Four lectures per week, Fall semester, 10 ECTS. The lectures are in person but will be recorded and linked to this site and the official University of Oslo website for the course;
+2. Two hours of laboratory sessions for work on computational projects and exercises for each group. There will also be fully digital laboratory sessions for those who cannot attend;
+3. Three projects which are graded and count 1/3 each of the final grade. The deadlines for the projects are October 11 for project 1, November 15 for project 2 and December 13 for project 3.
+4. A selected number of weekly assignments;
+5. The course is part of the CS Master of Science program, but is open to other bachelor and Master of Science students at the University of Oslo;
+6. The course is offered as a FYS-MAT4155 (Master of Science level) and a FYS-MAT3155 (senior undergraduate) course;
+7. Videos of teaching material are available via the links at https://compphysics.github.io/MachineLearning/doc/web/course.html;
+8. Weekly emails with summary of activities will be mailed to all participants;
+
+
+
+## Weekly Schedule
+
+For the reading assignments we use the following abbreviations:
+- GBC: Goodfellow, Bengio, and Courville, Deep Learning
+- CMB: Christopher M. Bishop, Pattern Recognition and Machine Learning
+- HTF: Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning
+- AG: Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow
+
+### Week 34 August 23-27
+- Lab Wednesday: Introduction to software and repetition of Python Programming
+- Lecture Thursday: Introduction to the course, what is Machine Learning and introduction to Linear Regression.
+- Video of Lecture August 26, 2021 at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage
+- Lecture Friday: Basics of Linear Regression
+- Video of Lecture August 27, 2021 at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage
+
+- Reading recommendations:
+ - Refresh linear algebra, GBC chapters 1 and 2.
+ - CMB sections 1.1 and 3.1.
+ - HTF chapters 2 and 3.
+ - See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html
+
+### Week 35 August 30-September 3
+- Lab Wednesday: Work on exercises 1-3 for week 35
+- Thursday: Review of ordinary Least Squares with applications and discussion of Ridge Regression and Singular Value Decomposition
+- Video of lecture Thursday at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember2.mp4?vrtx=view-as-webpage.
+- Friday: Analysis of Ridge and Lasso Regression and links with Singular Value Decomposition
+- Video of lecture Friday at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember3.mp4?vrtx=view-as-webpage
+
+- Reading recommendations:
+ - See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - HTF chapter 3. GBC chapters 1 and and sections 3.1-3.11 and 5.1
+ - CMB sections 1.1 and 3.1
+
+
+### Week 36 September 6-10
+- Lab Wednesday: Exercises 1 and 2 from week 36
+- Lecture Thursday: Summary from last week on SVD, Statistics, probability theory and linear regression
+- Video of Lecture https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember9.mp4?vrtx=view-as-webpage
+- Friday: Linear Regression and links with Statistics, Resampling methods and presentation of first project.
+- Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage
+
+- Reading recommendations:
+ - Lectures on Regression for week 36 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Bishop 1.1, 1.2, 2.1, 2.2, 2.3 and 3.1
+ - Hastie et al chapter 3
+
+### Week 37 September 13-17
+- Lab Wednesday: Work on Project 1
+- Lecture Thursday: Resampling methods, cross-validation and Bootstrap
+ - Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
+ - Video of Lecture, first part at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember16Firstpart.mp4?vrtx=view-as-webpage"
+ - Video of Lecture, second part at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember16SecondPart.mp4?vrtx=view-as-webpage
+- Lecture Friday: More on Resampling methods and summary of linear regression
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember17.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - Lectures on Resampling methods for week 37 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
+ - Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap)
+ - Goodfellow et al discuss some of these topics in sections 5.2-5.5.
+
+
+### Week 38 September 20-24
+- Lab Wednesday: Work on Project 1
+- Lecture Thursday: Classification problems and Logistic Regression, from binary cases to several categories
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureSeptember23.mp4?vrtx=view-as-webpage
+- Lecture Friday: Logistic Regression and gradient optimization
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember24.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 38 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Bishop 4.1, 4.2 and 4.3. Not all the material is relevant or will be covered. Section 4.3 is the most relevant, but 4.1 and 4.2 give interesting background readings for logistic regression
+ - Hastie et al 4.1, 4.2 and 4.3 on logistic regression
+ - For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.
+
+### Week 39 September 27- October 1
+- Lab Wednesday: Work on Project 1
+- Lecture Thursday: Gradient Optimization methods
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember30.mp4?vrtx=view-as-webpage
+- Lecture Friday: Gradient methods
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober1.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 39 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.
+
+
+
+### Week 40 October 4-8
+- Lab Wednesday: Wrap up project 1
+- Lecture Thursday: Stochastic gradient descent, automatic differentiation and start discussion of feed-forward Neural Network code for regression and classification
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober7.mp4?vrtx=view-as-webpage
+- Lecture Friday: Deep Learning and Neural Networks: the back propagation algorithm
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober8.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 40 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - For neural networks we recommend Goodfellow et al chapters 6 and 7 and Bishop 5.1-5.4
+ - For stochastic gradient descent we recommend Goodfellow et al chapter 8
+
+### Week 41 October 11-15
+- Lab Wednesday: Work on project 2
+- Lecture Thursday: Deep learning and Neural Networks, developing a code for Neural Networks
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober14.mp4?vrtx=view-as-webpage
+- Lecture Friday: Tensorflow and the mathematics of neural network
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureOctober15.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 41 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - For neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. chapter 11 and 12 on practicalities and applications
+
+
+### Week 42 October 18-22
+- Lab Wednesday: Work on project 2
+- Lecture Thursday: Solving differential equations with neural networks and start Convolutional Neural Networks and classification problems
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober21.mp4?vrtx=view-as-webpage
+- Lecture Friday: Convolutional Neural Networks and classification problems
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureOctober22.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 42 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - For neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications
+
+### Week 43 October 25-29
+- Lab Wednesday: Work on project 2
+- Lecture Thursday: Recurrent Neural Networks
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober28.mp4?vrtx=view-as-webpage
+- Lecture Friday: Recurrent Neural Networks and time series and principal component analysis (PCA)
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober29.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 43 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - For RNNs, see Goodfellow et al chapter 10 and discussions in chapter 11 and 12 on practicalities and applications
+ - For PCA, see lecture notes chapter 11 and Geron's text chapter 8
+### Week 44 November 1-5
+- Lab Wednesday: Work on project 2
+- Lecture Thursday: Summary on PCA and discussion of Clustering for unsupervised learning. Decision trees, classification and regression
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember4.mp4?vrtx=view-as-webpage
+- Lecture Friday: Decision trees, basic algorithms
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember5.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 44 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Hastie et al sections 9.1 and 9.2. Geron's text chapter 6 (Decision trees) and chapter 8 on PCA and Clustering
+
+### Week 45 November 8-12
+- Lab Wednesday: Work on project 2, project 3 available. Deadline project 2 is November 15.
+- Lecture Thursday: Ensemble methods, bagging and random forests
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember11.mp4?vrtx=view-as-webpage
+- Lecture Friday: Boosting and gradient boosting
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember12.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 45 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Hastie et al chapter 10
+
+### Week 46 November 15-19
+- Lab Wednesday: Work on project 3
+- Lecture Thursday: Support Vector machines
+- Lecture Friday: Workshop on project 3
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureNovember19.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 46 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Hastie et al chapter 12
+
+### Week 47 November 22-26
+- Lab Wednesday: Work on project 3
+- Lecture Thursday: Support Vector Machines
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureNovember25.mp4?vrtx=view-as-webpage
+- Lecture Friday: Support Vector Machines and Summary of course
+ - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember26.mp4?vrtx=view-as-webpage
+- Reading recommendations:
+ - See lecture notes for week 47 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
+ - Geron's chapter 5.
+ - Hastie et al Chapter 12 (sections 12.1-12.3 are the most relevant ones)
+ - Bishop chapter 7, with sections 7.1 and 7.2 as the essential ones
+
+
diff --git a/doc/LectureNotes/_build/html/_sources/statistics.ipynb b/doc/LectureNotes/_build/html/_sources/statistics.ipynb
new file mode 100644
index 000000000..8690ffe7a
--- /dev/null
+++ b/doc/LectureNotes/_build/html/_sources/statistics.ipynb
@@ -0,0 +1,2882 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Elements of Probability Theory and Statistical Data Analysis\n",
+ "\n",
+ "\n",
+ "## Domains and probabilities\n",
+ "Consider the following simple example, namely the tossing of two dice, resulting in the following possible values"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\{2,3,4,5,6,7,8,9,10,11,12\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "These values are called the *domain*. \n",
+ "To this domain we have the corresponding *probabilities*"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Tossing the dice\n",
+ "The numbers in the domain are the outcomes of the physical process of tossing say two dice.\n",
+ "We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain.\n",
+ "This defines the randomness of the outcome, or unexpectedness or any other synonimous word which\n",
+ "encompasses the uncertitude of the final outcome. \n",
+ "\n",
+ "The only thing we can tell beforehand\n",
+ "is that say the outcome 2 has a certain probability. \n",
+ "If our favorite hobby is to spend an hour every evening throwing dice and \n",
+ "registering the sequence of outcomes, we will note that the numbers in the above domain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\{2,3,4,5,6,7,8,9,10,11,12\\},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "appear in a random order. After 11 throws the results may look like"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\{10,8,6,3,6,9,11,8,12,4,5\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Stochastic variables\n",
+ "\n",
+ "**Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Stochastic variables and the main concepts, the discrete case\n",
+ "There are two main concepts associated with a stochastic variable. The\n",
+ "*domain* is the set $\\mathbb D = \\{x\\}$ of all accessible values\n",
+ "the variable can assume, so that $X \\in \\mathbb D$. An example of a\n",
+ "discrete domain is the set of six different numbers that we may get by\n",
+ "throwing of a dice, $x\\in\\{1,\\,2,\\,3,\\,4,\\,5,\\,6\\}$.\n",
+ "\n",
+ "The *probability distribution function (PDF)* is a function\n",
+ "$p(x)$ on the domain which, in the discrete case, gives us the\n",
+ "probability or relative frequency with which these values of $X$\n",
+ "occur"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\mathrm{Prob}(X=x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Stochastic variables and the main concepts, the continuous case\n",
+ "In the continuous case, the PDF does not directly depict the\n",
+ "actual probability. Instead we define the probability for the\n",
+ "stochastic variable to assume any value on an infinitesimal interval\n",
+ "around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\n",
+ "the *density* of the probability rather than the probability\n",
+ "itself. The probability for a stochastic variable to assume any value\n",
+ "on a non-infinitesimal interval $[a,\\,b]$ is then just the integral"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{Prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Qualitatively speaking, a stochastic variable represents the values of\n",
+ "numbers chosen as if by chance from some specified PDF so that the\n",
+ "selection of a large set of these numbers reproduces this PDF.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The cumulative probability\n",
+ "Of interest to us is the *cumulative probability\n",
+ "distribution function* (**CDF**), $P(x)$, which is just the probability\n",
+ "for a stochastic variable $X$ to assume any value less than $x$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(x)=\\mathrm{Prob(}X\\leq x\\mathrm{)} =\n",
+ "\\int_{-\\infty}^x p(x^{\\prime})dx^{\\prime}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The relation between a CDF and its corresponding PDF is then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\frac{d}{dx}P(x).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Properties of PDFs\n",
+ "\n",
+ "There are two properties that all PDFs must satisfy. The first one is\n",
+ "positivity (assuming that the PDF is normalized)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "0 \\leq p(x) \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Naturally, it would be nonsensical for any of the values of the domain\n",
+ "to occur with a probability greater than $1$ or less than $0$. Also,\n",
+ "the PDF must be normalized. That is, all the probabilities must add up\n",
+ "to unity. The probability of \"anything\" to happen is always unity. For\n",
+ "both discrete and continuous PDFs, this condition is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\sum_{x_i\\in\\mathbb D} p(x_i) & = 1,\\\\\n",
+ "\\int_{x\\in\\mathbb D} p(x)\\,dx & = 1.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Important distributions, the uniform distribution\n",
+ "The first one\n",
+ "is the most basic PDF; namely the uniform distribution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "p(x) = \\frac{1}{b-a}\\theta(x-a)\\theta(b-x).\n",
+ "\\label{eq:unifromPDF} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For $a=0$ and $b=1$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{array}{ll}\n",
+ "p(x)dx = dx & \\in [0,1].\n",
+ "\\end{array}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Gaussian distribution\n",
+ "The second one is the Gaussian Distribution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp{(-\\frac{(x-\\mu)^2}{2\\sigma^2})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with mean value $\\mu$ and standard deviation $\\sigma$. If $\\mu=0$ and $\\sigma=1$, it is normally called the **standard normal distribution**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\frac{1}{\\sqrt{2\\pi}} \\exp{(-\\frac{x^2}{2})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The following simple Python code plots the above distribution for different values of $\\mu$ and $\\sigma$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "from math import acos, exp, sqrt\n",
+ "from matplotlib import pyplot as plt\n",
+ "from matplotlib import rc, rcParams\n",
+ "import matplotlib.units as units\n",
+ "import matplotlib.ticker as ticker\n",
+ "rc('text',usetex=True)\n",
+ "rc('font',**{'family':'serif','serif':['Gaussian distribution']})\n",
+ "font = {'family' : 'serif',\n",
+ " 'color' : 'darkred',\n",
+ " 'weight' : 'normal',\n",
+ " 'size' : 16,\n",
+ " }\n",
+ "pi = acos(-1.0)\n",
+ "mu0 = 0.0\n",
+ "sigma0 = 1.0\n",
+ "mu1= 1.0\n",
+ "sigma1 = 2.0\n",
+ "mu2 = 2.0\n",
+ "sigma2 = 4.0\n",
+ "\n",
+ "x = np.linspace(-20.0, 20.0)\n",
+ "v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0)\n",
+ "v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1)\n",
+ "v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2)\n",
+ "plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-')\n",
+ "plt.title(r'{\\bf Gaussian distributions}', fontsize=20)\n",
+ "plt.text(-19, 0.3, r'Parameters: $\\mu = 0$, $\\sigma = 1$', fontdict=font)\n",
+ "plt.text(-19, 0.18, r'Parameters: $\\mu = 1$, $\\sigma = 2$', fontdict=font)\n",
+ "plt.text(-19, 0.08, r'Parameters: $\\mu = 2$, $\\sigma = 4$', fontdict=font)\n",
+ "plt.xlabel(r'$x$',fontsize=20)\n",
+ "plt.ylabel(r'$p(x)$ [MeV]',fontsize=20)\n",
+ "\n",
+ "# Tweak spacing to prevent clipping of ylabel \n",
+ "plt.subplots_adjust(left=0.15)\n",
+ "plt.savefig('gaussian.pdf', format='pdf')\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exponential distribution\n",
+ "Another important distribution in science is the exponential distribution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\alpha\\exp{-(\\alpha x)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Expectation values\n",
+ "Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic\n",
+ "variable $X$ whose PDF is $p(x)$. We define the *expectation value*\n",
+ "of $h$ with respect to $p$ as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\langle h \\rangle_X \\equiv \\int\\! h(x)p(x)\\,dx\n",
+ "\\label{eq:expectation_value_of_h_wrt_p} \\tag{2}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Whenever the PDF is known implicitly, like in this case, we will drop\n",
+ "the index $X$ for clarity. \n",
+ "A particularly useful class of special expectation values are the\n",
+ "*moments*. The $n$-th moment of the PDF $p$ is defined as\n",
+ "follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x^n \\rangle \\equiv \\int\\! x^n p(x)\\,dx\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Stochastic variables and the main concepts, mean values\n",
+ "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n",
+ "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n",
+ "and often denoted by the letter $\\mu$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x\\rangle = \\mu \\equiv \\int x p(x)dx,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for a continuous distribution and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x\\rangle = \\mu \\equiv \\sum_{i=1}^N x_i p(x_i),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "for a discrete distribution. \n",
+ "Qualitatively it represents the centroid or the average value of the\n",
+ "PDF and is therefore simply called the expectation value of $p(x)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Stochastic variables and the main concepts, central moments, the variance\n",
+ "\n",
+ "A special version of the moments is the set of *central moments*, the n-th central moment defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle (x-\\langle x\\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The zero-th and first central moments are both trivial, equal $1$ and\n",
+ "$0$, respectively. But the second central moment, known as the\n",
+ "*variance* of $p$, is of particular interest. For the stochastic\n",
+ "variable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{Var}(X)$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\sigma^2_X &=\\mathrm{Var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n",
+ "\\int (x-\\langle x\\rangle)^2 p(x)dx\\\\\n",
+ "& = \\int\\left(x^2 - 2 x \\langle x\\rangle^{2} +\\langle x\\rangle^2\\right)p(x)dx\\\\\n",
+ "& = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\\\\\n",
+ "& = \\langle x^2 \\rangle - \\langle x\\rangle^2\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the \n",
+ "**standard deviation** of $p$. It is the RMS (root-mean-square)\n",
+ "value of the deviation of the PDF from its mean value, interpreted\n",
+ "qualitatively as the \"spread\" of $p$ around its mean.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions\n",
+ "\n",
+ "The following table collects properties of probability distribution functions.\n",
+ "In our notation we reserve the label $p(x)$ for the probability of a certain event,\n",
+ "while $P(x)$ is the cumulative probability. \n",
+ "\n",
+ "\n",
+ "
\n",
+ "\n",
+ "
Discrete PDF
Continuous PDF
\n",
+ "\n",
+ "\n",
+ "
Domain
$\\left\\{x_1, x_2, x_3, \\dots, x_N\\right\\}$
$[a,b]$
\n",
+ "
Probability
$p(x_i)$
$p(x)dx$
\n",
+ "
Cumulative
$P_i=\\sum_{l=1}^ip(x_l)$
$P(x)=\\int_a^xp(t)dt$
\n",
+ "
Positivity
$0 \\le p(x_i) \\le 1$
$p(x) \\ge 0$
\n",
+ "
Positivity
$0 \\le P_i \\le 1$
$0 \\le P(x) \\le 1$
\n",
+ "
Monotonic
$P_i \\ge P_j$ if $x_i \\ge x_j$
$P(x_i) \\ge P(x_j)$ if $x_i \\ge x_j$
\n",
+ "
Normalization
$P_N=1$
$P(b)=1$
\n",
+ "\n",
+ "
\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions\n",
+ "With a PDF we can compute expectation values of selected quantities such as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x^k\\rangle=\\sum_{i=1}^{N}x_i^kp(x_i),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "if we have a discrete PDF or"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x^k\\rangle=\\int_a^b x^kp(x)dx,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "in the case of a continuous PDF. We have already defined the mean value $\\mu$\n",
+ "and the variance $\\sigma^2$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The three famous Probability Distribution Functions\n",
+ "\n",
+ "There are at least three PDFs which one may encounter. These are the\n",
+ "\n",
+ "**Uniform distribution**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x)=\\frac{1}{b-a}\\Theta(x-a)\\Theta(b-x),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "yielding probabilities different from zero in the interval $[a,b]$.\n",
+ "\n",
+ "**The exponential distribution**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x)=\\alpha \\exp{(-\\alpha x)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "yielding probabilities different from zero in the interval $[0,\\infty)$ and with mean value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = \\int_0^{\\infty}xp(x)dx=\\int_0^{\\infty}x\\alpha \\exp{(-\\alpha x)}dx=\\frac{1}{\\alpha},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with variance"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2=\\int_0^{\\infty}x^2p(x)dx-\\mu^2 = \\frac{1}{\\alpha^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Probability Distribution Functions, the normal distribution\n",
+ "Finally, we have the so-called univariate normal distribution, or just the **normal distribution**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x)=\\frac{1}{b\\sqrt{2\\pi}}\\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with probabilities different from zero in the interval $(-\\infty,\\infty)$.\n",
+ "The integral $\\int_{-\\infty}^{\\infty}\\exp{\\left(-(x^2\\right)}dx$ appears in many calculations, its value\n",
+ "is $\\sqrt{\\pi}$, a result we will need when we compute the mean value and the variance.\n",
+ "The mean value is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = \\int_0^{\\infty}xp(x)dx=\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}x \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which becomes with a suitable change of variables"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu =\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(a+b\\sqrt{2}y)\\exp{-y^2}dy=a.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Probability Distribution Functions, the normal distribution\n",
+ "Similarly, the variance becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}(x-\\mu)^2 \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and inserting the mean value and performing a variable change we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(b\\sqrt{2}y)^2\\exp{\\left(-y^2\\right)}dy=\n",
+ "\\frac{2b^2}{\\sqrt{\\pi}}\\int_{-\\infty}^{\\infty}y^2\\exp{\\left(-y^2\\right)}dy,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and performing a final integration by parts we obtain the well-known result $\\sigma^2=b^2$.\n",
+ "It is useful to introduce the standard normal distribution as well, defined by $\\mu=a=0$, viz. a distribution\n",
+ "centered around zero and with a variance $\\sigma^2=1$, leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " p(x)=\\frac{1}{\\sqrt{2\\pi}}\\exp{\\left(-\\frac{x^2}{2}\\right)}.\n",
+ "\\label{_auto1} \\tag{3}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Probability Distribution Functions, the cumulative distribution\n",
+ "\n",
+ "The exponential and uniform distributions have simple cumulative functions,\n",
+ "whereas the normal distribution does not, being proportional to the so-called\n",
+ "error function $erf(x)$, given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "P(x) = \\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^x\\exp{\\left(-\\frac{t^2}{2}\\right)}dt,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is difficult to evaluate in a quick way.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions, other important distribution\n",
+ "\n",
+ "Some other PDFs which one encounters often in the natural sciences are the binomial distribution"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} \\hspace{0.5cm}x=0,1,\\dots,n,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right\n",
+ "in case of a random walker. Note that $x$ is a discrete stochastic variable. \n",
+ "\n",
+ "The sequence of binomial trials is characterized by the following definitions\n",
+ "\n",
+ " * Every experiment is thought to consist of $N$ independent trials.\n",
+ "\n",
+ " * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker.\n",
+ "\n",
+ " * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions, the binomial distribution\n",
+ "\n",
+ "In order to compute the mean and variance we need to recall Newton's binomial\n",
+ "formula"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(a+b)^m=\\sum_{n=0}^m \\left(\\begin{array}{c} m \\\\ n\\end{array}\\right)a^nb^{m-n},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can be used to show that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{x=0}^n\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "the PDF is normalized to one. \n",
+ "The mean value is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = \\sum_{x=0}^n x\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} =\n",
+ "\\sum_{x=0}^n x\\frac{n!}{x!(n-x)!}y^x(1-y)^{n-x},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "resulting in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = \n",
+ "\\sum_{x=0}^n x\\frac{(n-1)!}{(x-1)!(n-1-(x-1))!}y^{x-1}(1-y)^{n-1-(x-1)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu=ny\\sum_{\\nu=0}^n\\left(\\begin{array}{c} n-1 \\\\ \\nu\\end{array}\\right)y^{\\nu}(1-y)^{n-1-\\nu} =ny(y+1-y)^{n-1}=ny.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The variance is slightly trickier to get. It reads $\\sigma^2=ny(1-y)$. \n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions, Poisson's distribution\n",
+ "\n",
+ "Another important distribution with discrete stochastic variables $x$ is \n",
+ "the Poisson model, which resembles the exponential distribution and reads"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(x) = \\frac{\\lambda^x}{x!} e^{-\\lambda} \\hspace{0.5cm}x=0,1,\\dots,;\\lambda > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case both the mean value and the variance are easier to calculate,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu = \\sum_{x=0}^{\\infty} x \\frac{\\lambda^x}{x!} e^{-\\lambda} = \\lambda e^{-\\lambda}\\sum_{x=1}^{\\infty}\n",
+ "\\frac{\\lambda^{x-1}}{(x-1)!}=\\lambda,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the variance is $\\sigma^2=\\lambda$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Probability Distribution Functions, Poisson's distribution\n",
+ "An example of applications of the Poisson distribution could be the counting\n",
+ "of the number of $\\alpha$-particles emitted from a radioactive source in a given time interval.\n",
+ "In the limit of $n\\rightarrow \\infty$ and for small probabilities $y$, the binomial distribution\n",
+ "approaches the Poisson distribution. Setting $\\lambda = ny$, with $y$ the probability for an event in\n",
+ "the binomial distribution we can show that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\lim_{n\\rightarrow \\infty}\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} e^{-\\lambda}=\\sum_{x=1}^{\\infty}\\frac{\\lambda^x}{x!} e^{-\\lambda}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Meet the covariance!\n",
+ "An important quantity in a statistical analysis is the so-called covariance. \n",
+ "\n",
+ "Consider the set $\\{X_i\\}$ of $n$\n",
+ "stochastic variables (not necessarily uncorrelated) with the\n",
+ "multivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\n",
+ "of the stochastic variables, $X_i$ and $X_j$, is defined as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\mathrm{Cov}(X_i,\\,X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle \n",
+ "\\label{_auto2} \\tag{4}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation} \n",
+ "=\\int\\cdots\\int (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n,\n",
+ "\\label{eq:def_covariance} \\tag{5}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x_i\\rangle =\n",
+ "\\int\\cdots\\int x_i P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Meet the covariance in matrix disguise\n",
+ "If we consider the above covariance as a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C_{ij} =\\mathrm{Cov}(X_i,\\,X_j),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "then the diagonal elements are just the familiar\n",
+ "variances, $C_{ii} = \\mathrm{Cov}(X_i,\\,X_i) = \\mathrm{Var}(X_i)$. It turns out that\n",
+ "all the off-diagonal elements are zero if the stochastic variables are\n",
+ "uncorrelated.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Covariance"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "from math import exp, sqrt\n",
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "def covariance(x, y, n):\n",
+ " sum = 0.0\n",
+ " mean_x = np.mean(x)\n",
+ " mean_y = np.mean(y)\n",
+ " for i in range(0, n):\n",
+ " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n",
+ " return sum/n\n",
+ "\n",
+ "n = 10\n",
+ "\n",
+ "x=np.random.normal(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "covxy = covariance(x,y,n)\n",
+ "print(covxy)\n",
+ "z = np.vstack((x, y))\n",
+ "c = np.cov(z.T)\n",
+ "\n",
+ "print(c)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Meet the covariance, uncorrelated events\n",
+ "\n",
+ "Consider the stochastic variables $X_i$ and $X_j$, ($i\\neq j$). We have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "Cov(X_i,\\,X_j) &= \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\\\\\n",
+ "&=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\\\\\n",
+ "&=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j \\rangle +\n",
+ "\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \\\\\n",
+ "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n",
+ "\\langle x_i\\rangle\\langle x_j\\rangle \\\\\n",
+ "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If $X_i$ and $X_j$ are independent (assuming $i \\neq j$), we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x_i x_j\\rangle = \\langle x_i\\rangle\\langle x_j\\rangle,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "Cov(X_i, X_j) = 0 \\hspace{0.1cm} (i\\neq j).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Numerical experiments and the covariance\n",
+ "\n",
+ "Now that we have constructed an idealized mathematical framework, let\n",
+ "us try to apply it to empirical observations. Examples of relevant\n",
+ "physical phenomena may be spontaneous decays of nuclei, or a purely\n",
+ "mathematical set of numbers produced by some deterministic\n",
+ "mechanism. It is the latter we will deal with, using so-called pseudo-random\n",
+ "number generators. In general our observations will contain only a limited set of\n",
+ "observables. We remind the reader that\n",
+ "a *stochastic process* is a process that produces sequentially a\n",
+ "chain of values"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Numerical experiments and the covariance\n",
+ "We will call these\n",
+ "values our *measurements* and the entire set as our measured\n",
+ "*sample*. The action of measuring all the elements of a sample\n",
+ "we will call a stochastic *experiment* (since, operationally,\n",
+ "they are often associated with results of empirical observation of\n",
+ "some physical or mathematical phenomena; precisely an experiment). We\n",
+ "assume that these values are distributed according to some \n",
+ "PDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\n",
+ "stochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\n",
+ "trying to determine the full distribution $p$ we are often only\n",
+ "interested in finding the few lowest moments, like the mean\n",
+ "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Numerical experiments and the covariance, actual situations\n",
+ "In practical situations however, a sample is always of finite size. Let that\n",
+ "size be $n$. The expectation value of a sample $\\alpha$, the **sample mean**, is then defined as follows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\langle x_{\\alpha} \\rangle \\equiv \\frac{1}{n}\\sum_{k=1}^n x_{\\alpha,k}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The *sample variance* is:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{Var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_{\\alpha,k} - \\langle x_{\\alpha} \\rangle)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with its square root being the *standard deviation of the sample*.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Numerical experiments and the covariance, our observables\n",
+ "You can think of the above observables as a set of quantities which define\n",
+ "a given experiment. This experiment is then repeated several times, say $m$ times.\n",
+ "The total average is then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\langle X_m \\rangle= \\frac{1}{m}\\sum_{\\alpha=1}^mx_{\\alpha}=\\frac{1}{mn}\\sum_{\\alpha, k} x_{\\alpha,k},\n",
+ "\\label{eq:exptmean} \\tag{6}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the last sums end at $m$ and $n$.\n",
+ "The total variance is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2_m= \\frac{1}{mn^2}\\sum_{\\alpha=1}^m(\\langle x_{\\alpha} \\rangle-\\langle X_m \\rangle)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\sigma^2_m=\\frac{1}{m}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle).\n",
+ "\\label{eq:exptvariance} \\tag{7}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Numerical experiments and the covariance, the sample variance\n",
+ "\n",
+ "We define also the sample variance $\\sigma^2$ of all $mn$ individual experiments as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\sigma^2=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)^2.\n",
+ "\\label{eq:sampleexptvariance} \\tag{8}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "These quantities, being known experimental values or the results from our calculations, \n",
+ "may differ, in some cases\n",
+ "significantly, from the similarly named\n",
+ "exact values for the mean value $\\mu_X$, the variance $\\mathrm{Var}(X)$\n",
+ "and the covariance $\\mathrm{Cov}(X,Y)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Numerical experiments and the covariance, central limit theorem\n",
+ "\n",
+ "The central limit theorem states that the PDF $\\tilde{p}(z)$ of\n",
+ "the average of $m$ random values corresponding to a PDF $p(x)$ \n",
+ "is a normal distribution whose mean is the \n",
+ "mean value of the PDF $p(x)$ and whose variance is the variance\n",
+ "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n",
+ "\n",
+ "The central limit theorem leads then to the well-known expression for the\n",
+ "standard deviation, given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_m=\n",
+ "\\frac{\\sigma}{\\sqrt{m}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Definition of Correlation Functions and Standard Deviation\n",
+ "Our estimate of the true average $\\mu_{X}$ is the sample mean $\\langle X_m \\rangle$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu_{X}^{\\phantom X} \\approx X_m=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n x_{\\alpha,k}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can then use Eq. ([7](#eq:exptvariance))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2_m=\\frac{1}{mn^2}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and rewrite it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma^2_m=\\frac{\\sigma^2}{n}+\\frac{2}{mn^2}\\sum_{\\alpha=1}^m\\sum_{k\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\kappa_d = \\frac{f_d}{\\sigma^2}\n",
+ "\\label{eq:autocorrelformal} \\tag{9}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us a useful measure of the correlation pair correlation\n",
+ "starting always at $1$ for $d=0$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Definition of Correlation Functions and Standard Deviation, sample variance\n",
+ "\n",
+ "The sample variance of the $mn$ experiments can now be\n",
+ "written in terms of the autocorrelation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\sigma_m^2=\\frac{\\sigma^2}{n}+\\frac{2}{n}\\cdot\\sigma^2\\sum_{d=1}^{n-1}\n",
+ "\\frac{f_d}{\\sigma^2}=\\left(1+2\\sum_{d=1}^{n-1}\\kappa_d\\right)\\frac{1}{n}\\sigma^2=\\frac{\\tau}{n}\\cdot\\sigma^2\n",
+ "\\label{eq:error_estimate_corr_time} \\tag{10}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we see that $\\sigma_m$ can be expressed in terms of the\n",
+ "uncorrelated sample variance times a correction factor $\\tau$ which\n",
+ "accounts for the correlation between measurements. We call this\n",
+ "correction factor the *autocorrelation time*"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n",
+ "\\label{eq:autocorrelation_time} \\tag{11}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "For a correlation free experiment, $\\tau$\n",
+ "equals 1.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Definition of Correlation Functions and Standard Deviation\n",
+ "From the point of view of\n",
+ "Eq. ([10](#eq:error_estimate_corr_time)) we can interpret a sequential\n",
+ "correlation as an effective reduction of the number of measurements by\n",
+ "a factor $\\tau$. The effective number of measurements becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "n_\\mathrm{eff} = \\frac{n}{\\tau}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To neglect the autocorrelation time $\\tau$ will always cause our\n",
+ "simple uncorrelated estimate of $\\sigma_m^2\\approx \\sigma^2/n$ to\n",
+ "be less than the true sample error. The estimate of the error will be\n",
+ "too \"good\". On the other hand, the calculation of the full\n",
+ "autocorrelation time poses an efficiency problem if the set of\n",
+ "measurements is very large. The solution to this problem is given by \n",
+ "more practically oriented methods like the blocking technique.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Code to compute the Covariance matrix and the Covariance"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "from math import exp, sqrt\n",
+ "from random import random, seed\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Sample covariance, note the factor 1/(n-1)\n",
+ "def covariance(x, y, n):\n",
+ " sum = 0.0\n",
+ " mean_x = np.mean(x)\n",
+ " mean_y = np.mean(y)\n",
+ " for i in range(0, n):\n",
+ " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n",
+ " return sum/(n-1.)\n",
+ "\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "z = x**3+np.random.normal(size=n)\n",
+ "print(np.mean(z))\n",
+ "covxx = covariance(x,x,n)\n",
+ "covyy = covariance(y,y,n)\n",
+ "covzz = covariance(z,z,n)\n",
+ "covxy = covariance(x,y,n)\n",
+ "covxz = covariance(x,z,n)\n",
+ "covyz = covariance(y,z,n)\n",
+ "print(covxx,covyy, covzz)\n",
+ "print(covxy,covxz, covyz)\n",
+ "w = np.vstack((x, y, z))\n",
+ "#print(w)\n",
+ "c = np.cov(w)\n",
+ "print(c)\n",
+ "#eigen = np.zeros(n)\n",
+ "Eigvals, Eigvecs = np.linalg.eig(c)\n",
+ "print(Eigvals)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Random Numbers\n",
+ "\n",
+ "Uniform deviates are just random numbers that lie within a specified range\n",
+ "(typically 0 to 1), with any one number in the range just as likely as any other. They\n",
+ "are, in other words, what you probably think random numbers are. However,\n",
+ "we want to distinguish uniform deviates from other sorts of random numbers, for\n",
+ "example numbers drawn from a normal (Gaussian) distribution of specified mean\n",
+ "and standard deviation. These other sorts of deviates are almost always generated by\n",
+ "performing appropriate operations on one or more uniform deviates, as we will see\n",
+ "in subsequent sections. So, a reliable source of random uniform deviates, the subject\n",
+ "of this section, is an essential building block for any sort of stochastic modeling\n",
+ "or Monte Carlo computer work.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random Numbers, better name: pseudo random numbers\n",
+ "\n",
+ "A disclaimer is however appropriate. It should be fairly obvious that \n",
+ "something as deterministic as a computer cannot generate purely random numbers.\n",
+ "\n",
+ "Numbers generated by any of the standard algorithms are in reality pseudo random\n",
+ "numbers, hopefully abiding to the following criteria:\n",
+ "\n",
+ " * they produce a uniform distribution in the interval [0,1].\n",
+ "\n",
+ " * correlations between random numbers are negligible\n",
+ "\n",
+ " * the period before the same sequence of random numbers is repeated is as large as possible and finally\n",
+ "\n",
+ " * the algorithm should be fast.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG\n",
+ " The most common random number generators are based on so-called\n",
+ "Linear congruential relations of the type"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_i=(aN_{i-1}+c) \\mathrm{MOD} (M),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yield a number in the interval [0,1] through"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "x_i=N_i/M\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The number \n",
+ "$M$ is called the period and it should be as large as possible \n",
+ " and \n",
+ "$N_0$ is the starting value, or seed. The function $\\mathrm{MOD}$ means the remainder,\n",
+ "that is if we were to evaluate $(13)\\mathrm{MOD}(9)$, the outcome is the remainder\n",
+ "of the division $13/9$, namely $4$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG and periodic outputs\n",
+ "\n",
+ "The problem with such generators is that their outputs are periodic;\n",
+ "they \n",
+ "will start to repeat themselves with a period that is at most $M$. If however\n",
+ "the parameters $a$ and $c$ are badly chosen, the period may be even shorter.\n",
+ "\n",
+ "Consider the following example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_i=(6N_{i-1}+7) \\mathrm{MOD} (5),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a seed $N_0=2$. This generator produces the sequence\n",
+ "$4,1,3,0,2,4,1,3,0,2,...\\dots$, i.e., a sequence with period $5$.\n",
+ "However, increasing $M$ may not guarantee a larger period as the following\n",
+ "example shows"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_i=(27N_{i-1}+11) \\mathrm{MOD} (54),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which still, with $N_0=2$, results in $11,38,11,38,11,38,\\dots$, a period of\n",
+ "just $2$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG and its period\n",
+ "Typical periods for the random generators provided in the program library \n",
+ "are of the order of $\\sim 10^9$ or larger. Other random number generators which have\n",
+ "become increasingly popular are so-called shift-register generators.\n",
+ "In these generators each successive number depends on many preceding\n",
+ "values (rather than the last values as in the linear congruential\n",
+ "generator).\n",
+ "For example, you could make a shift register generator whose $l$th \n",
+ "number is the sum of the $l-i$th and $l-j$th values with modulo $M$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_l=(aN_{l-i}+cN_{l-j})\\mathrm{MOD}(M).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Random number generator RNG, other examples\n",
+ "Such a generator again produces a sequence of pseudorandom numbers\n",
+ "but this time with a period much larger than $M$.\n",
+ "It is also possible to construct more elaborate algorithms by including\n",
+ "more than two past terms in the sum of each iteration.\n",
+ "One example is the generator of [Marsaglia and Zaman](http://dl.acm.org/citation.cfm?id=187154)\n",
+ "which consists of two congruential relations"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " N_l=(N_{l-3}-N_{l-1})\\mathrm{MOD}(2^{31}-69),\n",
+ "\\label{eq:mz1} \\tag{12}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "followed by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ " N_l=(69069N_{l-1}+1013904243)\\mathrm{MOD}(2^{32}),\n",
+ "\\label{eq:mz2} \\tag{13}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which according to the authors has a period larger than $2^{94}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG, other examples\n",
+ "Instead of using modular addition, we could use the bitwise\n",
+ "exclusive-OR ($\\oplus$) operation so that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_l=(N_{l-i})\\oplus (N_{l-j})\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the bitwise action of $\\oplus$ means that if $N_{l-i}=N_{l-j}$ the result is\n",
+ "$0$ whereas if $N_{l-i}\\ne N_{l-j}$ the result is\n",
+ "$1$. As an example, consider the case where $N_{l-i}=6$ and $N_{l-j}=11$. The first\n",
+ "one has a bit representation (using 4 bits only) which reads $0110$ whereas the \n",
+ "second number is $1011$. Employing the $\\oplus$ operator yields \n",
+ "$1101$, or $2^3+2^2+2^0=13$.\n",
+ "\n",
+ "In Fortran90, the bitwise $\\oplus$ operation is coded through the intrinsic\n",
+ "function $\\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$\n",
+ "it is given by $m\\wedge n$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG, RAN0\n",
+ "\n",
+ "We show here how the linear congruential algorithm can be implemented, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "N_i=(aN_{i-1}) \\mathrm{MOD} (M).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, since $a$ and $N_{i-1}$ are integers and their multiplication \n",
+ "could become greater than the standard 32 bit integer, there is a trick via \n",
+ "Schrage's algorithm which approximates the multiplication\n",
+ "of large integers through the factorization"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "M=aq+r,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have defined"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "q=[M/a],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "r = M\\hspace{0.1cm}\\mathrm{MOD} \\hspace{0.1cm}a.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the brackets denote integer division. In the code below the numbers \n",
+ "$q$ and $r$ are chosen so that $r < q$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG, RAN0\n",
+ "\n",
+ "To see how this works we note first that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q]M)\\mathrm{MOD} (M),\n",
+ "\\label{eq:rntrick1} \\tag{14}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$.\n",
+ "The last term $[N_{i-1}/q]M\\mathrm{MOD}(M)$ is zero since the integer division \n",
+ "$[N_{i-1}/q]$ just yields a constant which is multiplied with $M$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG, RAN0\n",
+ "We can now rewrite Eq. ([14](#eq:rntrick1)) as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q](aq+r))\\mathrm{MOD} (M),\n",
+ "\\label{eq:rntrick2} \\tag{15}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which results\n",
+ "in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}-[N_{i-1}/q]q)-[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M),\n",
+ "\\label{eq:rntrick3} \\tag{16}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "yielding"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}\\mathrm{MOD} (q)) -[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M).\n",
+ "\\label{eq:rntrick4} \\tag{17}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Random number generator RNG, RAN0\n",
+ "The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a \n",
+ "number smaller than $N_{i-1}$, which is smaller than $M$. \n",
+ "And since the number $N_{i-1}\\mathrm{MOD} (q)$ is between zero and $q-1$ then\n",
+ "$a(N_{i-1}\\mathrm{MOD} (q))< aq$. Combined with our definition of $q=[M/a]$ ensures that \n",
+ "this term is also smaller than $M$ meaning that both terms fit into a\n",
+ "32-bit signed integer. None of these two terms can be negative, but their difference could.\n",
+ "The algorithm below adds $M$ if their difference is negative.\n",
+ "Note that the program uses the bitwise $\\oplus$ operator to generate\n",
+ "the starting point for each generation of a random number. The period\n",
+ "of $ran0$ is $\\sim 2.1\\times 10^{9}$. A special feature of this\n",
+ "algorithm is that is should never be called with the initial seed \n",
+ "set to $0$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Random number generator RNG, RAN0 code"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ " /*\n",
+ " ** The function\n",
+ " ** ran0()\n",
+ " ** is an \"Minimal\" random number generator of Park and Miller\n",
+ " ** Set or reset the input value\n",
+ " ** idum to any integer value (except the unlikely value MASK)\n",
+ " ** to initialize the sequence; idum must not be altered between\n",
+ " ** calls for sucessive deviates in a sequence.\n",
+ " ** The function returns a uniform deviate between 0.0 and 1.0.\n",
+ " */\n",
+ " double ran0(long &idum)\n",
+ " {\n",
+ " const int a = 16807, m = 2147483647, q = 127773;\n",
+ " const int r = 2836, MASK = 123459876;\n",
+ " const double am = 1./m;\n",
+ " long k;\n",
+ " double ans;\n",
+ " idum ^= MASK;\n",
+ " k = (*idum)/q;\n",
+ " idum = a*(idum - k*q) - r*k;\n",
+ " // add m if negative difference\n",
+ " if(idum < 0) idum += m;\n",
+ " ans=am*(idum);\n",
+ " idum ^= MASK;\n",
+ " return ans;\n",
+ " } // End: function ran0() \n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Properties of Selected Random Number Generators\n",
+ "\n",
+ "As mentioned previously, the underlying PDF for the generation of\n",
+ "random numbers is the uniform distribution, meaning that the \n",
+ "probability for finding a number $x$ in the interval [0,1] is $p(x)=1$.\n",
+ "\n",
+ "A random number generator should produce numbers which are uniformly distributed\n",
+ "in this interval. The table shows the distribution of $N=10000$ random\n",
+ "numbers generated by the functions in the program library.\n",
+ "We note in this table that the number of points in the various\n",
+ "intervals $0.0-0.1$, $0.1-0.2$ etc are fairly close to $1000$, with some minor\n",
+ "deviations. \n",
+ "\n",
+ "Two additional measures are the standard deviation $\\sigma$ and the mean\n",
+ "$\\mu=\\langle x\\rangle$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Properties of Selected Random Number Generators\n",
+ "For the uniform distribution, the mean value $\\mu$ is then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mu=\\langle x\\rangle=\\frac{1}{2}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "while the standard deviation is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma=\\sqrt{\\langle x^2\\rangle-\\mu^2}=\\frac{1}{\\sqrt{12}}=0.2886.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Properties of Selected Random Number Generators\n",
+ "The various random number generators produce results which agree rather well with\n",
+ "these limiting values. \n",
+ "\n",
+ "