diff --git a/doc/src/DecisionTrees/chapter8.dlog b/doc/src/DecisionTrees/chapter8.dlog
new file mode 100644
index 000000000..77d16657b
--- /dev/null
+++ b/doc/src/DecisionTrees/chapter8.dlog
@@ -0,0 +1,7 @@
+*** error: file has a mako construction ${\cal C}'
+ but seemingly no definition in <%...%>'
+ (it is not a command-line given mako variable either).
+ However, if this is a variable in a Makefile or Bash script
+ run with --no_mako - and you cannot use mako and Makefile or Bash variables
+ in the same document!
+
diff --git a/doc/src/DecisionTrees/chapter8.do.txt b/doc/src/DecisionTrees/chapter8.do.txt
new file mode 100644
index 000000000..8331af647
--- /dev/null
+++ b/doc/src/DecisionTrees/chapter8.do.txt
@@ -0,0 +1,2347 @@
+TITLE: Data Analysis and Machine Learning:
+AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+DATE: today
+
+
+======= From Decision Trees to Forests and all that =======
+
+
+===== To do list =====
+
+* Make figures of trees that look better
+* improve Gini code and entropy code
+* develop full code for decision tree with CART algorithm
+* Work out better example for decsion tree with all calculations
+* develop better material for boosting, from ada boost to gradient boosting
+
+
+
+===== Decision trees, overarching aims =====
+
+
+We start here with the most basic algorithm, the so-called decision
+tree. With this basic algorithm we can in turn build more complex
+networks, spanning from homogeneous and heterogenous forests (bagging,
+random forests and more) to one of the most popular supervised
+algorithms nowadays, the extreme gradient boosting, or just
+XGBoost. But let us start with the simplest possible ingredient.
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+_information_ regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the _most
+informative_ feature is done until we accomplish a stopping criteria
+where we then finally end up in so called _leaf nodes_.
+
+
+
+A decision tree is typically divided into a _root node_, the _interior nodes_,
+and the final _leaf nodes_ or just _leaves_. These entities are then connected by so-called _branches_.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+
+===== A typical Decision Tree with its pertinent Jargon, Classification Problem =====
+
+FIGURE: [DataFiles/cancer.png, width=600 frac=0.8]
+
+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using _Scikit-Learn_'s decision tree classifier. Here we have used the so-called _gini_ index (see below) to split the various branches.
+
+
+
+
+===== General Features =====
+
+The overarching approach to decision trees is a top-down approach.
+
+* A leaf provides the classification of a given instance.
+* A node specifies a test of some attribute of the instance.
+* A branch corresponds to a possible values of an attribute.
+* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+
+===== How do we set it up? =====
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+o Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+o Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+o Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances
+
+o Show query instances to the tree and run down the tree until we arrive at leaf nodes
+
+Then we are essentially done!
+
+
+
+
+
+
+===== Decision trees and Regression =====
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0 and bestAttrId in attributeIds:
+ toRemove = attributeIds.index(bestAttrId)
+ attributeIds.pop(toRemove)
+ child.next = self.id3Recv(
+ childSampleIds, attributeIds, child.next)
+ return root
+
+ def printTree(self):
+ if self.root:
+ roots = deque()
+ roots.append(self.root)
+ while len(roots) > 0:
+ root = roots.popleft()
+ print(root.value)
+ if root.childs:
+ for child in root.childs:
+ print('({})'.format(child.value))
+ roots.append(child.next)
+ elif root.next:
+ print(root.next)
+
+
+def test():
+ f = open('DataFiles/rideclass.csv')
+ attributes = f.readline().split(',')
+ attributes = attributes[1:len(attributes)-1]
+ print(attributes)
+ sample = f.readlines()
+ f.close()
+ for i in range(len(sample)):
+ sample[i] = re.sub('\d+,', '', sample[i])
+ sample[i] = sample[i].strip().split(',')
+ labels = []
+ for s in sample:
+ labels.append(s.pop())
+ # print(sample)
+ # print(labels)
+ decisionTree = DecisionTree(sample, attributes, labels)
+ print("System entropy {}".format(decisionTree.entropy))
+ decisionTree.id3()
+ decisionTree.printTree()
+
+
+if __name__ == '__main__':
+ test()
+!ec
+
+
+===== Cancer Data again now with Decision Trees and other Methods =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+!ec
+
+
+
+===== Another example, the moons again =====
+!bc pycod
+from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if not iris:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ if plot_training:
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+ plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+ plt.axis(axes)
+ if iris:
+ plt.xlabel("Petal length", fontsize=14)
+ plt.ylabel("Petal width", fontsize=14)
+ else:
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+ if legend:
+ plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+!ec
+
+
+===== Playing around with regions =====
+!bc pycod
+np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+!ec
+
+
+===== Regression trees =====
+!bc pycod
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+!ec
+
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+!ec
+
+
+===== Final regressor code =====
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+!ec
+
+!bc pycod
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+!ec
+
+
+
+
+===== Pros and cons of trees, pros =====
+
+* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+* No feature normalization needed
+* Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+* Can model nonlinear relationships
+* Can model interactions between the different descriptive features
+* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+
+===== Disadvantages =====
+
+* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+* If continuous features are used the tree may become quite large and hence less interpretable
+* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+
+
+
+===== Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods =====
+
+As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+
+This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+
+o Voting classifiers
+o Bagging and Pasting
+o Random forests
+o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+
+We discuss these methods here.
+
+
+
+===== An Overview of Ensemble Methods =====
+
+FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8]
+
+
+
+
+===== Bagging =====
+
+The _plain_ decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+_Bootstrap aggregation_, or just _bagging_, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+
+===== More bagging =====
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+
+===== Simple Voting Example, head or tail =====
+!bc pycod
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+!ec
+
+
+===== Using the Voting Classifier =====
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+!ec
+
+
+===== Please, not the moons again! Voting and Bagging =====
+
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+
+===== Bagging Examples =====
+
+!bc pycod
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+!ec
+
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+!ec
+
+!bc pycod
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+!ec
+
+
+
+
+===== Making your own Bootstrap: Changing the Level of the Decision Tree =====
+
+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
+a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$).
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+!ec
+
+
+
+
+
+===== Random forests =====
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+!bt
+\[
+m\approx \sqrt{p}.
+\]
+!et
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quantities. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+
+===== Random Forest Algorithm =====
+The algorithm described here can be applied to both classification and regression problems.
+
+We will grow of forest of say $B$ trees.
+o For $b=1:B$
+ * Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix.
+ * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
+ o we select $m \le p$ variables at random from the $p$ predictors/features
+ o pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node
+ o split the node into daughter nodes
+o Output then the ensemble of trees $\{T_b\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem.
+
+
+
+
+===== Random Forests Compared with other Methods on the Cancer Data =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+!ec
+
+
+
+===== Compare Bagging on Trees with Random Forests =====
+!bc pycod
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+!ec
+
+
+
+!bc pycod
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+!ec
+
+
+
+
+
+
+===== Boosting, a Bird's Eye View =====
+
+The basic idea is to combine weak classifiers in order to create a good
+classifier. With a weak classifier we often intend a classifier which
+produces results which are only slightly better than we would get by
+random guesses.
+
+This is done by applying in an iterative way a weak (or a standard
+classifier like decision trees) to modify the data. In each iteration
+we emphasize those observations which are misclassified by weighting
+them with a factor.
+
+
+
+===== What is boosting? Additive Modelling/Iterative Fitting =====
+
+Boosting is a way of fitting an additive expansion in a set of
+elementary basis functions like for example some simple polynomials.
+Assume for example that we have a function
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+
+where $\beta_m$ are the expansion parameters to be determined in a
+minimization process and $b(x;\gamma_m)$ are some simple functions of
+the multivariable parameter $x$ which is characterized by the
+parameters $\gamma_m$.
+
+As an example, consider the Sigmoid function we used in logistic
+regression. In that case, we can translate the function
+$b(x;\gamma_m)$ into the Sigmoid function
+
+
+!bt
+\[
+\sigma(t) = \frac{1}{1+\exp{(-t)}},
+\]
+!et
+
+where $t=\gamma_0+\gamma_1 x$ and the parameters $\gamma_0$ and
+$\gamma_1$ were determined by the Logistic Regression fitting
+algorithm.
+
+As another example, consider the cost function we defined for linear regression
+!bt
+\[
+C(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+In this case the function $f(x)$ was replaced by the design matrix
+$\bm{X}$ and the unknown linear regression parameters $\bm{\beta}$,
+that is $\bm{f}=\bm{X}\bm{\beta}$. In linear regression we can
+simply invert a matrix and obtain the parameters $\beta$ by
+
+!bt
+\[
+\bm{\beta}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+
+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$.
+
+
+
+===== Iterative Fitting, Regression and Squared-error Cost Function =====
+
+The way we proceed is as follows (here we specialize to the squared-error cost function)
+
+o Establish a cost function, here ${\cal C}(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m)$.
+o Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.
+o For $m=1:M$
+ o minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$
+ o This gives the optimal values $\beta_m$ and $\gamma_m$
+ o Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$
+
+We could use any of the algorithms we have discussed till now. If we
+use trees, $\gamma$ parameterizes the split variables and split points
+at the internal nodes, and the predictions at the terminal nodes.
+
+
+
+===== Squared-Error Example and Iterative Fitting =====
+
+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+
+For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$.
+
+This means that for every iteration $m$, we need to optimize
+
+!bt
+\[
+(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
+\]
+!et
+
+We start our iteration by simply setting $f_0(x)=0$.
+Taking the derivatives with respect to $\beta$ and $\gamma$ we obtain
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
+\]
+!et
+We can then rewrite these equations as (defining $\bm{w}=\bm{e}+\gamma \bm{x})$ with $\bm{e}$ being the unit vector)
+!bt
+\[
+\gamma \bm{w}^T(\bm{y}-\beta\gamma \bm{w})=0,
+\]
+!et
+which gives us $\beta = \bm{w}^T\bm{y}/(\bm{w}^T\bm{w})$. Similarly we have
+!bt
+\[
+\beta\gamma \bm{x}^T(\bm{y}-\beta(1+\gamma \bm{x}))=0,
+\]
+!et
+
+which leads to $\gamma =(\bm{x}^T\bm{y}-\beta\bm{x}^T\bm{e})/(\beta\bm{x}^T\bm{x})$. Inserting
+for $\beta$ gives us an equation for $\gamma$. This is a non-linear equation in the unknown $\gamma$ and has to be solved numerically.
+
+The solution to these two equations gives us in turn $\beta_1$ and $\gamma_1$ leading to the new expression for $f_1(x)$ as
+$f_1(x) = \beta_1(1+\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$.
+
+
+
+
+===== Iterative Fitting, Classification and AdaBoost =====
+
+Let us consider a binary classification problem with two outcomes $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values
+$\{-1,1\}$.
+
+The error rate of the training sample is then
+
+!bt
+\[
+\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
+\]
+!et
+
+The iterative procedure starts with defining a weak classifier whose
+error rate is barely better than random guessing. The iterative
+procedure in boosting is to sequentially apply a weak
+classification algorithm to repeatedly modified versions of the data
+producing a sequence of weak classifiers $G_m(x)$.
+
+Here we will express our function $f(x)$ in terms of $G(x)$. That is
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+will be a function of
+!bt
+\[
+G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
+\]
+!et
+
+
+
+
+===== Adaptive Boosting, AdaBoost =====
+
+In our iterative procedure we define thus
+!bt
+\[
+f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
+\]
+!et
+
+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
+exponential cost/loss function defined as
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
+\]
+!et
+
+We optimize $\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.
+This is normally done in two steps. Let us however first rewrite the cost function as
+
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
+\]
+!et
+where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$.
+
+
+===== Building up AdaBoost =====
+
+First, for any $\beta > 0$, we optimize $G$ by setting
+!bt
+\[
+G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
+\]
+!et
+which is the classifier that minimizes the weighted error rate in predicting $y$.
+
+We can do this by rewriting
+!bt
+\[
+\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
+\]
+!et
+which can be rewritten as
+!bt
+\[
+(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
+\]
+!et
+which leads to
+!bt
+\[
+\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
+\]
+!et
+where we have redefined the error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
+\]
+!et
+which leads to an update of
+!bt
+\[
+f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
+\]
+!et
+This leads to the new weights
+!bt
+\[
+w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
+\]
+!et
+
+
+
+===== Adaptive boosting: AdaBoost, Basic Algorithm =====
+
+The algorithm here is rather straightforward. Assume that our weak
+classifier is a decision tree and we consider a binary set of outputs
+with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. Our design matrix is given in terms of the
+feature/predictor vectors
+$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}]$. Finally, we define also a
+classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$.
+
+We have already defined the misclassification error $\mathrm{err}$ as
+!bt
+\[
+\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
+\]
+!et
+where the function $I()$ is one if we misclassify and zero if we classify correctly.
+
+
+===== Basic Steps of AdaBoost =====
+
+With the above definitions we are now ready to set up the algorithm for AdaBoost.
+The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
+o We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is easy to see that we must have $\sum_{i=0}^{n-1}w_i = 1$.
+o We rewrite the misclassification error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
+\]
+!et
+o Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.
+ o Fit then a given classifier to the training set using the weights $w_i$.
+ o Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.
+ o Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$
+ o Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$.
+o Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$.
+
+For the iterations with $m \le 2$ the weights are modified
+individually at each steps. The observations which were misclassified
+at iteration $m-1$ have a weight which is larger than those which were
+classified properly. As this proceeds, the observations which were
+difficult to classifiy correctly are given a larger influence. Each
+new classification step $m$ is then forced to concentrate on those
+observations that are missed in the previous iterations.
+
+
+
+
+===== AdaBoost Examples =====
+
+Using _Scikit-Learn_ it is easy to apply the adaptive boosting algorithm, as done here.
+
+!bc pycod
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+!ec
+
+
+
+===== AdaBoost for Regression =====
+
+Here we present "Drucker's AdaBoost":"https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf" tailored for regression.
+
+In bagging, each training example is equally likely to be
+picked. In boosting, the probability of a particular
+example being in the training set of a particular machine
+depends on the performance of the prior machines on
+that example. The following is a modification of
+Adaboost by Drucker.
+
+Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\dots,n$. As we have done earlier, we could pick say $80\%$ of the data set for training. The algorithm runs as follows:
+o We define the probability that the training sample $i$ is in the set by $p_i = w_i/\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\sum_iw_i]$.
+o We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
+o Using every member of the training set with the chosen regression machine we obtain then a prediction $\tilde{y}_i$.
+o We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value
+$L_i\in [0,1]$.
+
+
+===== Gradient boosting: Basics with Steepest Descent =====
+
+Gradient boosting is again a similar technique to Adaptive boosting,
+it combines so-called weak classifiers or regressors into a strong
+method via a series of iterations.
+
+In order to understand the method, let us illustrate its basics by
+bringing back the essential steps in linear regression, where our cost
+function was the least squares function.
+
+
+===== The Squared-Error again! Steepest Descent =====
+
+We start again with our cost function ${\cal C}(\bm{y}m\bm{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i))$ where we want to minimize
+This means that for every iteration, we need to optimize
+
+!bt
+\[
+(\hat{\bm{f}}) = \mathrm{argmin}_{\bm{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as
+!bt
+\[
+f_M(x) = \sum_{m=0}^M h_m(x).
+\]
+!et
+
+In the steepest decent approach we approximate $h_m(x) = -\rho_m g_m(x)$, where $\rho_m$ is a scalar and $g_m(x)$ the gradient defined as
+!bt
+\[
+g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
+\]
+!et
+
+With the new gradient we can update $f_m(x) = f_{m-1}(x) -\rho_m g_m(x)$. Using the above squared-error function we see that
+the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.
+
+Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have
+!bt
+\[
+(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
+\]
+!et
+
+
+===== Steepest Descent Example =====
+
+Optimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that
+!bt
+\[
+f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
+\]
+!et
+We can then proceed and compute
+!bt
+\[
+g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,
+\]
+!et
+and find a new value for $\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called _gradient boosting_.
+
+
+===== Gradient Boosting, algorithm =====
+
+Suppose we have a cost function $C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function
+!bt
+\[
+C(\bm{y},\bm{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+The way we proceed in an iterative fashion is to
+o Initialize our estimate $f_0(x)$.
+o For $m=1:M$, we
+ o compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x)$;
+ o fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;
+ o update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$;
+o The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$.
+
+
+===== Gradient Boosting Example, Regression =====
+
+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above.
+
+
+
+===== Gradient Boosting, Examples of Regression =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+ model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+!ec
+
+
+
+===== Gradient Boosting, Classification Example =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+!ec
+
+
+
+===== XGBoost: Extreme Gradient Boosting =====
+
+
+"XGBoost":"https://github.com/dmlc/xgboost" or Extreme Gradient
+Boosting, is an optimized distributed gradient boosting library
+designed to be highly efficient, flexible and portable. It implements
+machine learning algorithms under the Gradient Boosting
+framework. XGBoost provides a parallel tree boosting that solve many
+data science problems in a fast and accurate way. See the "article by Chen and Guestrin":"https://arxiv.org/abs/1603.02754".
+
+The authors design and build a highly scalable end-to-end tree
+boosting system. It has a theoretically justified weighted quantile
+sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.
+
+It is now the algorithm which wins essentially all ML competitions!!!
+
+
+===== Regression Case =====
+
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+ model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+!ec
+
+
+===== Xgboost on the Cancer Data =====
+
+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+!ec
diff --git a/doc/src/DecisionTrees/chapter8.do.txt~ b/doc/src/DecisionTrees/chapter8.do.txt~
new file mode 100644
index 000000000..8ec2c6a9a
--- /dev/null
+++ b/doc/src/DecisionTrees/chapter8.do.txt~
@@ -0,0 +1,2344 @@
+TITLE: Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+DATE: today
+
+!split
+===== To do list =====
+
+* Make figures of trees that look better
+* improve Gini code and entropy code
+* develop full code for decision tree with CART algorithm
+* Work out better example for decsion tree with all calculations
+* develop better material for boosting, from ada boost to gradient boosting
+
+
+!split
+===== Decision trees, overarching aims =====
+
+
+We start here with the most basic algorithm, the so-called decision
+tree. With this basic algorithm we can in turn build more complex
+networks, spanning from homogeneous and heterogenous forests (bagging,
+random forests and more) to one of the most popular supervised
+algorithms nowadays, the extreme gradient boosting, or just
+XGBoost. But let us start with the simplest possible ingredient.
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+_information_ regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the _most
+informative_ feature is done until we accomplish a stopping criteria
+where we then finally end up in so called _leaf nodes_.
+
+
+
+A decision tree is typically divided into a _root node_, the _interior nodes_,
+and the final _leaf nodes_ or just _leaves_. These entities are then connected by so-called _branches_.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+!split
+===== A typical Decision Tree with its pertinent Jargon, Classification Problem =====
+
+FIGURE: [DataFiles/cancer.png, width=600 frac=0.8]
+
+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using _Scikit-Learn_'s decision tree classifier. Here we have used the so-called _gini_ index (see below) to split the various branches.
+
+
+
+!split
+===== General Features =====
+
+The overarching approach to decision trees is a top-down approach.
+
+* A leaf provides the classification of a given instance.
+* A node specifies a test of some attribute of the instance.
+* A branch corresponds to a possible values of an attribute.
+* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+!split
+===== How do we set it up? =====
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+o Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+o Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+o Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances
+
+o Show query instances to the tree and run down the tree until we arrive at leaf nodes
+
+Then we are essentially done!
+
+
+
+
+
+!split
+===== Decision trees and Regression =====
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0 and bestAttrId in attributeIds:
+ toRemove = attributeIds.index(bestAttrId)
+ attributeIds.pop(toRemove)
+ child.next = self.id3Recv(
+ childSampleIds, attributeIds, child.next)
+ return root
+
+ def printTree(self):
+ if self.root:
+ roots = deque()
+ roots.append(self.root)
+ while len(roots) > 0:
+ root = roots.popleft()
+ print(root.value)
+ if root.childs:
+ for child in root.childs:
+ print('({})'.format(child.value))
+ roots.append(child.next)
+ elif root.next:
+ print(root.next)
+
+
+def test():
+ f = open('DataFiles/rideclass.csv')
+ attributes = f.readline().split(',')
+ attributes = attributes[1:len(attributes)-1]
+ print(attributes)
+ sample = f.readlines()
+ f.close()
+ for i in range(len(sample)):
+ sample[i] = re.sub('\d+,', '', sample[i])
+ sample[i] = sample[i].strip().split(',')
+ labels = []
+ for s in sample:
+ labels.append(s.pop())
+ # print(sample)
+ # print(labels)
+ decisionTree = DecisionTree(sample, attributes, labels)
+ print("System entropy {}".format(decisionTree.entropy))
+ decisionTree.id3()
+ decisionTree.printTree()
+
+
+if __name__ == '__main__':
+ test()
+!ec
+
+!split
+===== Cancer Data again now with Decision Trees and other Methods =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+!ec
+
+
+!split
+===== Another example, the moons again =====
+!bc pycod
+from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if not iris:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ if plot_training:
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+ plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+ plt.axis(axes)
+ if iris:
+ plt.xlabel("Petal length", fontsize=14)
+ plt.ylabel("Petal width", fontsize=14)
+ else:
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+ if legend:
+ plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+!ec
+
+!split
+===== Playing around with regions =====
+!bc pycod
+np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+!ec
+
+!split
+===== Regression trees =====
+!bc pycod
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+!ec
+
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+!ec
+
+!split
+===== Final regressor code =====
+!bc pycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+!ec
+
+!bc pycod
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+!ec
+
+
+
+!split
+===== Pros and cons of trees, pros =====
+
+* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+* No feature normalization needed
+* Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+* Can model nonlinear relationships
+* Can model interactions between the different descriptive features
+* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+!split
+===== Disadvantages =====
+
+* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+* If continuous features are used the tree may become quite large and hence less interpretable
+* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+
+
+!split
+===== Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods =====
+
+As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+
+This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+
+o Voting classifiers
+o Bagging and Pasting
+o Random forests
+o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+
+We discuss these methods here.
+
+
+!split
+===== An Overview of Ensemble Methods =====
+
+FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8]
+
+
+
+!split
+===== Bagging =====
+
+The _plain_ decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+_Bootstrap aggregation_, or just _bagging_, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+!split
+===== More bagging =====
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+!split
+===== Simple Voting Example, head or tail =====
+!bc pycod
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+!ec
+
+!split
+===== Using the Voting Classifier =====
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+!ec
+
+!split
+===== Please, not the moons again! Voting and Bagging =====
+
+!bc pycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+!ec
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+!ec
+
+!split
+===== Bagging Examples =====
+
+!bc pycod
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+!ec
+
+
+!bc pycod
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+!ec
+
+!bc pycod
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+!ec
+
+!bc pycod
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+!ec
+
+
+
+!split
+===== Making your own Bootstrap: Changing the Level of the Decision Tree =====
+
+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
+a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$).
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+!ec
+
+
+
+
+!split
+===== Random forests =====
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+!bt
+\[
+m\approx \sqrt{p}.
+\]
+!et
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quantities. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+!split
+===== Random Forest Algorithm =====
+The algorithm described here can be applied to both classification and regression problems.
+
+We will grow of forest of say $B$ trees.
+o For $b=1:B$
+ * Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix.
+ * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
+ o we select $m \le p$ variables at random from the $p$ predictors/features
+ o pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node
+ o split the node into daughter nodes
+o Output then the ensemble of trees $\{T_b\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem.
+
+
+
+!split
+===== Random Forests Compared with other Methods on the Cancer Data =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+!ec
+
+
+!split
+===== Compare Bagging on Trees with Random Forests =====
+!bc pycod
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+!ec
+
+
+
+!bc pycod
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+!ec
+
+
+
+
+
+!split
+===== Boosting, a Bird's Eye View =====
+
+The basic idea is to combine weak classifiers in order to create a good
+classifier. With a weak classifier we often intend a classifier which
+produces results which are only slightly better than we would get by
+random guesses.
+
+This is done by applying in an iterative way a weak (or a standard
+classifier like decision trees) to modify the data. In each iteration
+we emphasize those observations which are misclassified by weighting
+them with a factor.
+
+
+!split
+===== What is boosting? Additive Modelling/Iterative Fitting =====
+
+Boosting is a way of fitting an additive expansion in a set of
+elementary basis functions like for example some simple polynomials.
+Assume for example that we have a function
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+
+where $\beta_m$ are the expansion parameters to be determined in a
+minimization process and $b(x;\gamma_m)$ are some simple functions of
+the multivariable parameter $x$ which is characterized by the
+parameters $\gamma_m$.
+
+As an example, consider the Sigmoid function we used in logistic
+regression. In that case, we can translate the function
+$b(x;\gamma_m)$ into the Sigmoid function
+
+
+!bt
+\[
+\sigma(t) = \frac{1}{1+\exp{(-t)}},
+\]
+!et
+
+where $t=\gamma_0+\gamma_1 x$ and the parameters $\gamma_0$ and
+$\gamma_1$ were determined by the Logistic Regression fitting
+algorithm.
+
+As another example, consider the cost function we defined for linear regression
+!bt
+\[
+C(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+In this case the function $f(x)$ was replaced by the design matrix
+$\bm{X}$ and the unknown linear regression parameters $\bm{\beta}$,
+that is $\bm{f}=\bm{X}\bm{\beta}$. In linear regression we can
+simply invert a matrix and obtain the parameters $\beta$ by
+
+!bt
+\[
+\bm{\beta}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+
+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$.
+
+
+!split
+===== Iterative Fitting, Regression and Squared-error Cost Function =====
+
+The way we proceed is as follows (here we specialize to the squared-error cost function)
+
+o Establish a cost function, here ${\cal C}(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m)$.
+o Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.
+o For $m=1:M$
+ o minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$
+ o This gives the optimal values $\beta_m$ and $\gamma_m$
+ o Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$
+
+We could use any of the algorithms we have discussed till now. If we
+use trees, $\gamma$ parameterizes the split variables and split points
+at the internal nodes, and the predictions at the terminal nodes.
+
+
+!split
+===== Squared-Error Example and Iterative Fitting =====
+
+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+
+For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$.
+
+This means that for every iteration $m$, we need to optimize
+
+!bt
+\[
+(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
+\]
+!et
+
+We start our iteration by simply setting $f_0(x)=0$.
+Taking the derivatives with respect to $\beta$ and $\gamma$ we obtain
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
+\]
+!et
+We can then rewrite these equations as (defining $\bm{w}=\bm{e}+\gamma \bm{x})$ with $\bm{e}$ being the unit vector)
+!bt
+\[
+\gamma \bm{w}^T(\bm{y}-\beta\gamma \bm{w})=0,
+\]
+!et
+which gives us $\beta = \bm{w}^T\bm{y}/(\bm{w}^T\bm{w})$. Similarly we have
+!bt
+\[
+\beta\gamma \bm{x}^T(\bm{y}-\beta(1+\gamma \bm{x}))=0,
+\]
+!et
+
+which leads to $\gamma =(\bm{x}^T\bm{y}-\beta\bm{x}^T\bm{e})/(\beta\bm{x}^T\bm{x})$. Inserting
+for $\beta$ gives us an equation for $\gamma$. This is a non-linear equation in the unknown $\gamma$ and has to be solved numerically.
+
+The solution to these two equations gives us in turn $\beta_1$ and $\gamma_1$ leading to the new expression for $f_1(x)$ as
+$f_1(x) = \beta_1(1+\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$.
+
+
+
+!split
+===== Iterative Fitting, Classification and AdaBoost =====
+
+Let us consider a binary classification problem with two outcomes $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values
+$\{-1,1\}$.
+
+The error rate of the training sample is then
+
+!bt
+\[
+\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
+\]
+!et
+
+The iterative procedure starts with defining a weak classifier whose
+error rate is barely better than random guessing. The iterative
+procedure in boosting is to sequentially apply a weak
+classification algorithm to repeatedly modified versions of the data
+producing a sequence of weak classifiers $G_m(x)$.
+
+Here we will express our function $f(x)$ in terms of $G(x)$. That is
+!bt
+\[
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+\]
+!et
+will be a function of
+!bt
+\[
+G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
+\]
+!et
+
+
+
+!split
+===== Adaptive Boosting, AdaBoost =====
+
+In our iterative procedure we define thus
+!bt
+\[
+f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
+\]
+!et
+
+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
+exponential cost/loss function defined as
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
+\]
+!et
+
+We optimize $\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.
+This is normally done in two steps. Let us however first rewrite the cost function as
+
+!bt
+\[
+C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
+\]
+!et
+where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$.
+
+!split
+===== Building up AdaBoost =====
+
+First, for any $\beta > 0$, we optimize $G$ by setting
+!bt
+\[
+G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
+\]
+!et
+which is the classifier that minimizes the weighted error rate in predicting $y$.
+
+We can do this by rewriting
+!bt
+\[
+\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
+\]
+!et
+which can be rewritten as
+!bt
+\[
+(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
+\]
+!et
+which leads to
+!bt
+\[
+\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
+\]
+!et
+where we have redefined the error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
+\]
+!et
+which leads to an update of
+!bt
+\[
+f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
+\]
+!et
+This leads to the new weights
+!bt
+\[
+w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
+\]
+!et
+
+
+!split
+===== Adaptive boosting: AdaBoost, Basic Algorithm =====
+
+The algorithm here is rather straightforward. Assume that our weak
+classifier is a decision tree and we consider a binary set of outputs
+with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
+observations. Our design matrix is given in terms of the
+feature/predictor vectors
+$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}]$. Finally, we define also a
+classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$.
+
+We have already defined the misclassification error $\mathrm{err}$ as
+!bt
+\[
+\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
+\]
+!et
+where the function $I()$ is one if we misclassify and zero if we classify correctly.
+
+!split
+===== Basic Steps of AdaBoost =====
+
+With the above definitions we are now ready to set up the algorithm for AdaBoost.
+The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
+o We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is easy to see that we must have $\sum_{i=0}^{n-1}w_i = 1$.
+o We rewrite the misclassification error as
+!bt
+\[
+\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
+\]
+!et
+o Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.
+ o Fit then a given classifier to the training set using the weights $w_i$.
+ o Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.
+ o Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$
+ o Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$.
+o Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$.
+
+For the iterations with $m \le 2$ the weights are modified
+individually at each steps. The observations which were misclassified
+at iteration $m-1$ have a weight which is larger than those which were
+classified properly. As this proceeds, the observations which were
+difficult to classifiy correctly are given a larger influence. Each
+new classification step $m$ is then forced to concentrate on those
+observations that are missed in the previous iterations.
+
+
+
+!split
+===== AdaBoost Examples =====
+
+Using _Scikit-Learn_ it is easy to apply the adaptive boosting algorithm, as done here.
+
+!bc pycod
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=1), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+!ec
+
+
+!split
+===== AdaBoost for Regression =====
+
+Here we present "Drucker's AdaBoost":"https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf" tailored for regression.
+
+In bagging, each training example is equally likely to be
+picked. In boosting, the probability of a particular
+example being in the training set of a particular machine
+depends on the performance of the prior machines on
+that example. The following is a modification of
+Adaboost by Drucker.
+
+Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\dots,n$. As we have done earlier, we could pick say $80\%$ of the data set for training. The algorithm runs as follows:
+o We define the probability that the training sample $i$ is in the set by $p_i = w_i/\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\sum_iw_i]$.
+o We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
+o Using every member of the training set with the chosen regression machine we obtain then a prediction $\tilde{y}_i$.
+o We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value
+$L_i\in [0,1]$.
+
+!split
+===== Gradient boosting: Basics with Steepest Descent =====
+
+Gradient boosting is again a similar technique to Adaptive boosting,
+it combines so-called weak classifiers or regressors into a strong
+method via a series of iterations.
+
+In order to understand the method, let us illustrate its basics by
+bringing back the essential steps in linear regression, where our cost
+function was the least squares function.
+
+!split
+===== The Squared-Error again! Steepest Descent =====
+
+We start again with our cost function ${\cal C}(\bm{y}m\bm{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i))$ where we want to minimize
+This means that for every iteration, we need to optimize
+
+!bt
+\[
+(\hat{\bm{f}}) = \mathrm{argmin}_{\bm{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as
+!bt
+\[
+f_M(x) = \sum_{m=0}^M h_m(x).
+\]
+!et
+
+In the steepest decent approach we approximate $h_m(x) = -\rho_m g_m(x)$, where $\rho_m$ is a scalar and $g_m(x)$ the gradient defined as
+!bt
+\[
+g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
+\]
+!et
+
+With the new gradient we can update $f_m(x) = f_{m-1}(x) -\rho_m g_m(x)$. Using the above squared-error function we see that
+the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.
+
+Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have
+!bt
+\[
+(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
+\]
+!et
+
+!split
+===== Steepest Descent Example =====
+
+Optimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that
+!bt
+\[
+f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
+\]
+!et
+We can then proceed and compute
+!bt
+\[
+g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,
+\]
+!et
+and find a new value for $\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called _gradient boosting_.
+
+!split
+===== Gradient Boosting, algorithm =====
+
+Suppose we have a cost function $C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function
+!bt
+\[
+C(\bm{y},\bm{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+\]
+!et
+
+The way we proceed in an iterative fashion is to
+o Initialize our estimate $f_0(x)$.
+o For $m=1:M$, we
+ o compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x)$;
+ o fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;
+ o update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$;
+o The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$.
+
+!split
+===== Gradient Boosting Example, Regression =====
+
+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above.
+
+
+!split
+===== Gradient Boosting, Examples of Regression =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+ model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+!ec
+
+
+!split
+===== Gradient Boosting, Classification Example =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+!ec
+
+
+!split
+===== XGBoost: Extreme Gradient Boosting =====
+
+
+"XGBoost":"https://github.com/dmlc/xgboost" or Extreme Gradient
+Boosting, is an optimized distributed gradient boosting library
+designed to be highly efficient, flexible and portable. It implements
+machine learning algorithms under the Gradient Boosting
+framework. XGBoost provides a parallel tree boosting that solve many
+data science problems in a fast and accurate way. See the "article by Chen and Guestrin":"https://arxiv.org/abs/1603.02754".
+
+The authors design and build a highly scalable end-to-end tree
+boosting system. It has a theoretically justified weighted quantile
+sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.
+
+It is now the algorithm which wins essentially all ML competitions!!!
+
+!split
+===== Regression Case =====
+
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+ model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+!ec
+
+!split
+===== Xgboost on the Cancer Data =====
+
+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.
+!bc pycod
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+!ec
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter1.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter1.doctree
index f4bd7cfe6..3657701e8 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/chapter1.doctree and b/doc/src/LectureNotes/_build/.doctrees/chapter1.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter2.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter2.doctree
index 60b977c26..94baf2ba4 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/chapter2.doctree and b/doc/src/LectureNotes/_build/.doctrees/chapter2.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter3.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter3.doctree
index 3e0cd4649..eff307cdb 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/chapter3.doctree and b/doc/src/LectureNotes/_build/.doctrees/chapter3.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter4.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter4.doctree
index e36e1ca28..ad50241a3 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/chapter4.doctree and b/doc/src/LectureNotes/_build/.doctrees/chapter4.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter8.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter8.doctree
index 3bb9844ca..9daeb94bf 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/chapter8.doctree and b/doc/src/LectureNotes/_build/.doctrees/chapter8.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/chapter9.doctree b/doc/src/LectureNotes/_build/.doctrees/chapter9.doctree
new file mode 100644
index 000000000..d851430c8
Binary files /dev/null and b/doc/src/LectureNotes/_build/.doctrees/chapter9.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/environment.pickle b/doc/src/LectureNotes/_build/.doctrees/environment.pickle
index 25b1690a3..a0d0a0bc1 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/environment.pickle and b/doc/src/LectureNotes/_build/.doctrees/environment.pickle differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/testbook/_build/jupyter_execute/chapter2.doctree b/doc/src/LectureNotes/_build/.doctrees/testbook/_build/jupyter_execute/chapter2.doctree
index c06177aa6..9cb6b7b93 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/testbook/_build/jupyter_execute/chapter2.doctree and b/doc/src/LectureNotes/_build/.doctrees/testbook/_build/jupyter_execute/chapter2.doctree differ
diff --git a/doc/src/LectureNotes/_build/.doctrees/testbook/chapter2.doctree b/doc/src/LectureNotes/_build/.doctrees/testbook/chapter2.doctree
index e47ad9c96..596968e92 100644
Binary files a/doc/src/LectureNotes/_build/.doctrees/testbook/chapter2.doctree and b/doc/src/LectureNotes/_build/.doctrees/testbook/chapter2.doctree differ
diff --git a/doc/src/LectureNotes/_build/html/_images/chapter2_178_0.png b/doc/src/LectureNotes/_build/html/_images/chapter2_178_0.png
index c5a3d04f2..80d8fd112 100644
Binary files a/doc/src/LectureNotes/_build/html/_images/chapter2_178_0.png and b/doc/src/LectureNotes/_build/html/_images/chapter2_178_0.png differ
diff --git a/doc/src/LectureNotes/_build/html/_images/chapter2_184_1.png b/doc/src/LectureNotes/_build/html/_images/chapter2_184_1.png
index babfb1319..c7b66ed0b 100644
Binary files a/doc/src/LectureNotes/_build/html/_images/chapter2_184_1.png and b/doc/src/LectureNotes/_build/html/_images/chapter2_184_1.png differ
diff --git a/doc/src/LectureNotes/_build/html/_images/chapter4_278_2.png b/doc/src/LectureNotes/_build/html/_images/chapter4_278_2.png
index 5a4fe5abe..a56a44f78 100644
Binary files a/doc/src/LectureNotes/_build/html/_images/chapter4_278_2.png and b/doc/src/LectureNotes/_build/html/_images/chapter4_278_2.png differ
diff --git a/doc/src/LectureNotes/_build/html/_images/chapter8_77_1.png b/doc/src/LectureNotes/_build/html/_images/chapter8_77_1.png
index 6509bb8be..50f345c7f 100644
Binary files a/doc/src/LectureNotes/_build/html/_images/chapter8_77_1.png and b/doc/src/LectureNotes/_build/html/_images/chapter8_77_1.png differ
diff --git a/doc/src/LectureNotes/_build/html/_images/chapter9_3_1.png b/doc/src/LectureNotes/_build/html/_images/chapter9_3_1.png
new file mode 100644
index 000000000..c160fc3d6
Binary files /dev/null and b/doc/src/LectureNotes/_build/html/_images/chapter9_3_1.png differ
diff --git a/doc/src/LectureNotes/_build/html/_sources/chapter9.ipynb b/doc/src/LectureNotes/_build/html/_sources/chapter9.ipynb
new file mode 100644
index 000000000..790a41066
--- /dev/null
+++ b/doc/src/LectureNotes/_build/html/_sources/chapter9.ipynb
@@ -0,0 +1,1441 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Convolutional Neural Networks\n",
+ "\n",
+ "\n",
+ "Convolutional neural networks (CNNs) were developed during the last\n",
+ "decade of the previous century, with a focus on character recognition\n",
+ "tasks. Nowadays, CNNs are a central element in the spectacular success\n",
+ "of deep learning methods. The success in for example image\n",
+ "classifications have made them a central tool for most machine\n",
+ "learning practitioners.\n",
+ "\n",
+ "CNNs are very similar to ordinary Neural Networks.\n",
+ "They are made up of neurons that have learnable weights and\n",
+ "biases. Each neuron receives some inputs, performs a dot product and\n",
+ "optionally follows it with a non-linearity. The whole network still\n",
+ "expresses a single differentiable score function: from the raw image\n",
+ "pixels on one end to class scores at the other. And they still have a\n",
+ "loss function (for example Softmax) on the last (fully-connected) layer\n",
+ "and all the tips/tricks we developed for learning regular Neural\n",
+ "Networks still apply (back propagation, gradient descent etc etc).\n",
+ "\n",
+ "What is the difference? **CNN architectures make the explicit assumption that\n",
+ "the inputs are images, which allows us to encode certain properties\n",
+ "into the architecture. These then make the forward function more\n",
+ "efficient to implement and vastly reduce the amount of parameters in\n",
+ "the network.**\n",
+ "\n",
+ "Here we provide only a superficial overview, for the more interested, we recommend highly the course\n",
+ "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
+ "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n",
+ "\n",
+ "Another good read is the article here . \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Neural Networks vs CNNs\n",
+ "\n",
+ "Neural networks are defined as **affine transformations**, that is \n",
+ "a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n",
+ "output (to which a bias vector is usually added before passing the result\n",
+ "through a nonlinear activation function). This is applicable to any type of input, be it an\n",
+ "image, a sound clip or an unordered collection of features: whatever their\n",
+ "dimensionality, their representation can always be flattened into a vector\n",
+ "before the transformation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Why CNNS for images, sound files, medical images from CT scans etc?\n",
+ "\n",
+ "However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n",
+ "structure. More formally, they share these important properties:\n",
+ "* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n",
+ "\n",
+ "* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n",
+ "\n",
+ "* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n",
+ "\n",
+ "These properties are not exploited when an affine transformation is applied; in\n",
+ "fact, all the axes are treated in the same way and the topological information\n",
+ "is not taken into account. Still, taking advantage of the implicit structure of\n",
+ "the data may prove very handy in solving some tasks, like computer vision and\n",
+ "speech recognition, and in these cases it would be best to preserve it. This is\n",
+ "where discrete convolutions come into play.\n",
+ "\n",
+ "A discrete convolution is a linear transformation that preserves this notion of\n",
+ "ordering. It is sparse (only a few input units contribute to a given output\n",
+ "unit) and reuses parameters (the same weights are applied to multiple locations\n",
+ "in the input).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Regular NNs don’t scale well to full images\n",
+ "\n",
+ "As an example, consider\n",
+ "an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n",
+ "single fully-connected neuron in a first hidden layer of a regular\n",
+ "Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n",
+ "seems manageable, but clearly this fully-connected structure does not\n",
+ "scale to larger images. For example, an image of more respectable\n",
+ "size, say $200\\times 200\\times 3$, would lead to neurons that have \n",
+ "$200\\times 200\\times 3 = 120,000$ weights. \n",
+ "\n",
+ "We could have\n",
+ "several such neurons, and the parameters would add up quickly! Clearly,\n",
+ "this full connectivity is wasteful and the huge number of parameters\n",
+ "would quickly lead to possible overfitting.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "
A regular 3-layer Neural Network.
\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## 3D volumes of neurons\n",
+ "\n",
+ "Convolutional Neural Networks take advantage of the fact that the\n",
+ "input consists of images and they constrain the architecture in a more\n",
+ "sensible way. \n",
+ "\n",
+ "In particular, unlike a regular Neural Network, the\n",
+ "layers of a CNN have neurons arranged in 3 dimensions: width,\n",
+ "height, depth. (Note that the word depth here refers to the third\n",
+ "dimension of an activation volume, not to the depth of a full Neural\n",
+ "Network, which can refer to the total number of layers in a network.)\n",
+ "\n",
+ "To understand it better, the above example of an image \n",
+ "with an input volume of\n",
+ "activations has dimensions $32\\times 32\\times 3$ (width, height,\n",
+ "depth respectively). \n",
+ "\n",
+ "The neurons in a layer will\n",
+ "only be connected to a small region of the layer before it, instead of\n",
+ "all of the neurons in a fully-connected manner. Moreover, the final\n",
+ "output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n",
+ "because by the\n",
+ "end of the CNN architecture we will reduce the full image into a\n",
+ "single vector of class scores, arranged along the depth\n",
+ "dimension. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "
A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Layers used to build CNNs\n",
+ "\n",
+ "\n",
+ "A simple CNN is a sequence of layers, and every layer of a CNN\n",
+ "transforms one volume of activations to another through a\n",
+ "differentiable function. We use three main types of layers to build\n",
+ "CNN architectures: Convolutional Layer, Pooling Layer, and\n",
+ "Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n",
+ "will stack these layers to form a full CNN architecture.\n",
+ "\n",
+ "A simple CNN for image classification could have the architecture:\n",
+ "\n",
+ "* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n",
+ "\n",
+ "* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n",
+ "\n",
+ "* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n",
+ "\n",
+ "* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n",
+ "\n",
+ "* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n",
+ "\n",
+ "## Transforming images\n",
+ "\n",
+ "CNNs transform the original image layer by layer from the original\n",
+ "pixel values to the final class scores. \n",
+ "\n",
+ "Observe that some layers contain\n",
+ "parameters and other don’t. In particular, the CNN layers perform\n",
+ "transformations that are a function of not only the activations in the\n",
+ "input volume, but also of the parameters (the weights and biases of\n",
+ "the neurons). On the other hand, the RELU/POOL layers will implement a\n",
+ "fixed function. The parameters in the CONV/FC layers will be trained\n",
+ "with gradient descent so that the class scores that the CNN computes\n",
+ "are consistent with the labels in the training set for each image.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## CNNs in brief\n",
+ "\n",
+ "In summary:\n",
+ "\n",
+ "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
+ "\n",
+ "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
+ "\n",
+ "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
+ "\n",
+ "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n",
+ "\n",
+ "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
+ "\n",
+ "For more material on convolutional networks, we strongly recommend\n",
+ "the course\n",
+ "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
+ "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
+ "\n",
+ "\n",
+ "As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
+ "to the network are 2D images. This is important because the number of features or pixels in images\n",
+ "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
+ "\n",
+ "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
+ "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
+ "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
+ "matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Setting it up\n",
+ "\n",
+ "It means that to represent the entire\n",
+ "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The MNIST dataset again\n",
+ "\n",
+ "The MNIST dataset consists of grayscale images with a pixel size of\n",
+ "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
+ "neuron in the first hidden layer.\n",
+ "\n",
+ "If we were to analyze images of size $128\\times 128$ we would require\n",
+ "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
+ "dealing with color images, as most images are, we have an image matrix\n",
+ "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
+ "meaning 3 times the number of weights $= 49152$ are required for every\n",
+ "single neuron in the first hidden layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Strong correlations\n",
+ "\n",
+ "Images typically have strong local correlations, meaning that a small\n",
+ "part of the image varies little from its neighboring regions. If for\n",
+ "example we have an image of a blue car, we can roughly assume that a\n",
+ "small blue part of the image is surrounded by other blue regions.\n",
+ "\n",
+ "Therefore, instead of connecting every single pixel to a neuron in the\n",
+ "first hidden layer, as we have previously done with deep neural\n",
+ "networks, we can instead connect each neuron to a small part of the\n",
+ "image (in all 3 RGB depth dimensions). The size of each small area is\n",
+ "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Layers of a CNN\n",
+ "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
+ "The input image is typically a square matrix of depth 3. \n",
+ "\n",
+ "A **convolution** is performed on the image which outputs\n",
+ "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
+ "\n",
+ "\n",
+ "Each filter slides along the input image, taking the dot product\n",
+ "between each small part of the image and the filter, in all depth\n",
+ "dimensions. This is then passed through a non-linear function,\n",
+ "typically the **Rectified Linear (ReLu)** function, which serves as the\n",
+ "activation of the neurons in the first convolutional layer. This is\n",
+ "further passed through a **pooling layer**, which reduces the size of the\n",
+ "convolutional layer, e.g. by taking the maximum or average across some\n",
+ "small regions, and this serves as input to the next convolutional\n",
+ "layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Systematic reduction\n",
+ "\n",
+ "By systematically reducing the size of the input volume, through\n",
+ "convolution and pooling, the network should create representations of\n",
+ "small parts of the input, and then from them assemble representations\n",
+ "of larger areas. The final pooling layer is flattened to serve as\n",
+ "input to a hidden layer, such that each neuron in the final pooling\n",
+ "layer is connected to every single neuron in the hidden layer. This\n",
+ "then serves as input to the output layer, e.g. a softmax output for\n",
+ "classification.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Prerequisites: Collect and pre-process data"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "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",
+ "# RGB images have a depth of 3\n",
+ "# our images are grayscale so they should have a depth of 1\n",
+ "inputs = inputs[:,:,:,np.newaxis]\n",
+ "\n",
+ "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
+ "print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
+ "\n",
+ "\n",
+ "# choose some random images to display\n",
+ "n_inputs = len(inputs)\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": [
+ "## Importing Keras and Tensorflow"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from tensorflow.keras import datasets, layers, models\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",
+ "#from tensorflow.keras import Conv2D\n",
+ "#from tensorflow.keras import MaxPooling2D\n",
+ "#from tensorflow.keras import Flatten\n",
+ "\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "\n",
+ "# representation of labels\n",
+ "labels = to_categorical(labels)\n",
+ "\n",
+ "# split into train and test data\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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Running with Keras"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
+ " n_filters, n_neurons_connected, n_categories,\n",
+ " eta, lmbd):\n",
+ " model = Sequential()\n",
+ " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
+ " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
+ " model.add(layers.Flatten())\n",
+ " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " \n",
+ " sgd = optimizers.SGD(lr=eta)\n",
+ " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
+ " \n",
+ " return model\n",
+ "\n",
+ "epochs = 100\n",
+ "batch_size = 100\n",
+ "input_shape = X_train.shape[1:4]\n",
+ "receptive_field = 3\n",
+ "n_filters = 10\n",
+ "n_neurons_connected = 50\n",
+ "n_categories = 10\n",
+ "\n",
+ "eta_vals = np.logspace(-5, 1, 7)\n",
+ "lmbd_vals = np.logspace(-5, 1, 7)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Final part"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "CNN_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",
+ " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
+ " n_filters, n_neurons_connected, n_categories,\n",
+ " eta, lmbd)\n",
+ " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
+ " scores = CNN.evaluate(X_test, Y_test)\n",
+ " \n",
+ " CNN_keras[i][j] = CNN\n",
+ " \n",
+ " print(\"Learning rate = \", eta)\n",
+ " print(\"Lambda = \", lmbd)\n",
+ " print(\"Test accuracy: %.3f\" % scores[1])\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Final visualization"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# 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",
+ " CNN = CNN_keras[i][j]\n",
+ "\n",
+ " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
+ " test_accuracy[i][j] = CNN.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 CIFAR01 data set\n",
+ "\n",
+ "The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n",
+ "6,000 images in each class. The dataset is divided into 50,000\n",
+ "training images and 10,000 testing images. The classes are mutually\n",
+ "exclusive and there is no overlap between them."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import tensorflow as tf\n",
+ "\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# We import the data set\n",
+ "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n",
+ "\n",
+ "# Normalize pixel values to be between 0 and 1 by dividing by 255. \n",
+ "train_images, test_images = train_images / 255.0, test_images / 255.0"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Verifying the data set\n",
+ "\n",
+ "To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
+ " 'dog', 'frog', 'horse', 'ship', 'truck']\n",
+ "\n",
+ "plt.figure(figsize=(10,10))\n",
+ "for i in range(25):\n",
+ " plt.subplot(5,5,i+1)\n",
+ " plt.xticks([])\n",
+ " plt.yticks([])\n",
+ " plt.grid(False)\n",
+ " plt.imshow(train_images[i], cmap=plt.cm.binary)\n",
+ " # The CIFAR labels happen to be arrays, \n",
+ " # which is why you need the extra index\n",
+ " plt.xlabel(class_names[train_labels[i][0]])\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Set up the model\n",
+ "\n",
+ "The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n",
+ "\n",
+ "As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model = models.Sequential()\n",
+ "model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n",
+ "model.add(layers.MaxPooling2D((2, 2)))\n",
+ "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
+ "model.add(layers.MaxPooling2D((2, 2)))\n",
+ "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
+ "\n",
+ "# Let's display the architecture of our model so far.\n",
+ "\n",
+ "model.summary()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Add Dense layers on top\n",
+ "\n",
+ "To complete our model, you will feed the last output tensor from the\n",
+ "convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n",
+ "to perform classification. Dense layers take vectors as input (which\n",
+ "are 1D), while the current output is a 3D tensor. First, you will\n",
+ "flatten (or unroll) the 3D output to 1D, then add one or more Dense\n",
+ "layers on top. CIFAR has 10 output classes, so you use a final Dense\n",
+ "layer with 10 outputs and a softmax activation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model.add(layers.Flatten())\n",
+ "model.add(layers.Dense(64, activation='relu'))\n",
+ "model.add(layers.Dense(10))\n",
+ "Here's the complete architecture of our model.\n",
+ "\n",
+ "model.summary()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.\n",
+ "\n",
+ "\n",
+ "## Compile and train the model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model.compile(optimizer='adam',\n",
+ " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
+ " metrics=['accuracy'])\n",
+ "\n",
+ "history = model.fit(train_images, train_labels, epochs=10, \n",
+ " validation_data=(test_images, test_labels))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Finally, evaluate the model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "plt.plot(history.history['accuracy'], label='accuracy')\n",
+ "plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n",
+ "plt.xlabel('Epoch')\n",
+ "plt.ylabel('Accuracy')\n",
+ "plt.ylim([0.5, 1])\n",
+ "plt.legend(loc='lower right')\n",
+ "\n",
+ "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n",
+ "\n",
+ "print(test_acc)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Recurrent neural networks: Overarching view\n",
+ "\n",
+ "Till now our focus has been, including convolutional neural networks\n",
+ "as well, on feedforward neural networks. The output or the activations\n",
+ "flow only in one direction, from the input layer to the output layer.\n",
+ "\n",
+ "A recurrent neural network (RNN) looks very much like a feedforward\n",
+ "neural network, except that it also has connections pointing\n",
+ "backward. \n",
+ "\n",
+ "RNNs are used to analyze time series data such as stock prices, and\n",
+ "tell you when to buy or sell. In autonomous driving systems, they can\n",
+ "anticipate car trajectories and help avoid accidents. More generally,\n",
+ "they can work on sequences of arbitrary lengths, rather than on\n",
+ "fixed-sized inputs like all the nets we have discussed so far. For\n",
+ "example, they can take sentences, documents, or audio samples as\n",
+ "input, making them extremely useful for natural language processing\n",
+ "systems such as automatic translation and speech-to-text.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Set up of an RNN\n",
+ "\n",
+ "\n",
+ "Text to come.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## A simple example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# Start importing packages\n",
+ "import pandas as pd\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import tensorflow as tf\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Model, Sequential \n",
+ "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
+ "from tensorflow.keras import optimizers \n",
+ "from tensorflow.keras import regularizers \n",
+ "from tensorflow.keras.utils import to_categorical \n",
+ "\n",
+ "\n",
+ "\n",
+ "# convert into dataset matrix\n",
+ "def convertToMatrix(data, step):\n",
+ " X, Y =[], []\n",
+ " for i in range(len(data)-step):\n",
+ " d=i+step \n",
+ " X.append(data[i:d,])\n",
+ " Y.append(data[d,])\n",
+ " return np.array(X), np.array(Y)\n",
+ "\n",
+ "step = 4\n",
+ "N = 1000 \n",
+ "Tp = 800 \n",
+ "\n",
+ "t=np.arange(0,N)\n",
+ "x=np.sin(0.02*t)+2*np.random.rand(N)\n",
+ "df = pd.DataFrame(x)\n",
+ "df.head()\n",
+ "\n",
+ "plt.plot(df)\n",
+ "plt.show()\n",
+ "\n",
+ "values=df.values\n",
+ "train,test = values[0:Tp,:], values[Tp:N,:]\n",
+ "\n",
+ "# add step elements into train and test\n",
+ "test = np.append(test,np.repeat(test[-1,],step))\n",
+ "train = np.append(train,np.repeat(train[-1,],step))\n",
+ " \n",
+ "trainX,trainY =convertToMatrix(train,step)\n",
+ "testX,testY =convertToMatrix(test,step)\n",
+ "trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
+ "testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
+ "\n",
+ "model = Sequential()\n",
+ "model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
+ "model.add(Dense(8, activation=\"relu\")) \n",
+ "model.add(Dense(1))\n",
+ "model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
+ "model.summary()\n",
+ "\n",
+ "model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
+ "trainPredict = model.predict(trainX)\n",
+ "testPredict= model.predict(testX)\n",
+ "predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
+ "\n",
+ "trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
+ "print(trainScore)\n",
+ "\n",
+ "index = df.index.values\n",
+ "plt.plot(index,df)\n",
+ "plt.plot(index,predicted)\n",
+ "plt.axvline(df.index[Tp], c=\"r\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## An extrapolation example\n",
+ "\n",
+ "The following code provides an example of how recurrent neural\n",
+ "networks can be used to extrapolate to unknown values of physics data\n",
+ "sets. Specifically, the data sets used in this program come from\n",
+ "a quantum mechanical many-body calculation of energies as functions of the number of particles."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "# For matrices and calculations\n",
+ "import numpy as np\n",
+ "# For machine learning (backend for keras)\n",
+ "import tensorflow as tf\n",
+ "# User-friendly machine learning library\n",
+ "# Front end for TensorFlow\n",
+ "import tensorflow.keras\n",
+ "# Different methods from Keras needed to create an RNN\n",
+ "# This is not necessary but it shortened function calls \n",
+ "# that need to be used in the code.\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras import regularizers\n",
+ "from tensorflow.keras.models import Model, Sequential\n",
+ "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
+ "# For timing the code\n",
+ "from timeit import default_timer as timer\n",
+ "# For plotting\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "\n",
+ "# The data set\n",
+ "datatype='VaryDimension'\n",
+ "X_tot = np.arange(2, 42, 2)\n",
+ "y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n",
+ "\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n",
+ "\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Formatting the Data\n",
+ "\n",
+ "The way the recurrent neural networks are trained in this program\n",
+ "differs from how machine learning algorithms are usually trained.\n",
+ "Typically a machine learning algorithm is trained by learning the\n",
+ "relationship between the x data and the y data. In this program, the\n",
+ "recurrent neural network will be trained to recognize the relationship\n",
+ "in a sequence of y values. This is type of data formatting is\n",
+ "typically used time series forcasting, but it can also be used in any\n",
+ "extrapolation (time series forecasting is just a specific type of\n",
+ "extrapolation along the time axis). This method of data formatting\n",
+ "does not use the x data and assumes that the y data are evenly spaced.\n",
+ "\n",
+ "For a standard machine learning algorithm, the training data has the\n",
+ "form of (x,y) so the machine learning algorithm learns to assiciate a\n",
+ "y value with a given x value. This is useful when the test data has x\n",
+ "values within the same range as the training data. However, for this\n",
+ "application, the x values of the test data are outside of the x values\n",
+ "of the training data and the traditional method of training a machine\n",
+ "learning algorithm does not work as well. For this reason, the\n",
+ "recurrent neural network is trained on sequences of y values of the\n",
+ "form ((y1, y2), y3), so that the network is concerned with learning\n",
+ "the pattern of the y data and not the relation between the x and y\n",
+ "data. As long as the pattern of y data outside of the training region\n",
+ "stays relatively stable compared to what was inside the training\n",
+ "region, this method of training can produce accurate extrapolations to\n",
+ "y values far removed from the training data set.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# FORMAT_DATA\n",
+ "def format_data(data, length_of_sequence = 2): \n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " data(a numpy array): the data that will be the inputs to the recurrent neural\n",
+ " network\n",
+ " length_of_sequence (an int): the number of elements in one iteration of the\n",
+ " sequence patter. For a function approximator use length_of_sequence = 2.\n",
+ " Returns:\n",
+ " rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n",
+ " dimensions are length of data - length of sequence, length of sequence, \n",
+ " dimnsion of data\n",
+ " rnn_output (a numpy array): the training data for the neural network\n",
+ " Formats data to be used in a recurrent neural network.\n",
+ " \"\"\"\n",
+ "\n",
+ " X, Y = [], []\n",
+ " for i in range(len(data)-length_of_sequence):\n",
+ " # Get the next length_of_sequence elements\n",
+ " a = data[i:i+length_of_sequence]\n",
+ " # Get the element that immediately follows that\n",
+ " b = data[i+length_of_sequence]\n",
+ " # Reshape so that each data point is contained in its own array\n",
+ " a = np.reshape (a, (len(a), 1))\n",
+ " X.append(a)\n",
+ " Y.append(b)\n",
+ " rnn_input = np.array(X)\n",
+ " rnn_output = np.array(Y)\n",
+ "\n",
+ " return rnn_input, rnn_output\n",
+ "\n",
+ "\n",
+ "# ## Defining the Recurrent Neural Network Using Keras\n",
+ "# \n",
+ "# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n",
+ "\n",
+ "def rnn(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons in the input and output layers\n",
+ " in_out_neurons = 1\n",
+ " # Number of neurons in the hidden layer\n",
+ " hidden_neurons = 200\n",
+ " # Define the input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n",
+ " # the network immediately after the input layer\n",
+ " rnn = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\")(inp)\n",
+ " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
+ " #and add it to the network immediately after the hidden layer.\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
+ " # Create the machine learning model starting with the input layer and ending with the \n",
+ " # output layer\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the machine learning model using the mean squared error function as the loss \n",
+ " # function and an Adams optimizer.\n",
+ " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
+ " return model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Predicting New Points With A Trained Recurrent Neural Network"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def test_rnn (x1, y_test, plot_min, plot_max):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " x1 (a list or numpy array): The complete x component of the data set\n",
+ " y_test (a list or numpy array): The complete y component of the data set\n",
+ " plot_min (an int or float): the smallest x value used in the training data\n",
+ " plot_max (an int or float): the largest x valye used in the training data\n",
+ " Returns:\n",
+ " None.\n",
+ " Uses a trained recurrent neural network model to predict future points in the \n",
+ " series. Computes the MSE of the predicted data set from the true data set, saves\n",
+ " the predicted data set to a csv file, and plots the predicted and true data sets w\n",
+ " while also displaying the data range used for training.\n",
+ " \"\"\"\n",
+ " # Add the training data as the first dim points in the predicted data array as these\n",
+ " # are known values.\n",
+ " y_pred = y_test[:dim].tolist()\n",
+ " # Generate the first input to the trained recurrent neural network using the last two \n",
+ " # points of the training data. Based on how the network was trained this means that it\n",
+ " # will predict the first point in the data set after the training data. All of the \n",
+ " # brackets are necessary for Tensorflow.\n",
+ " next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n",
+ " # Save the very last point in the training data set. This will be used later.\n",
+ " last = [y_test[dim-1]]\n",
+ "\n",
+ " # Iterate until the complete data set is created.\n",
+ " for i in range (dim, len(y_test)):\n",
+ " # Predict the next point in the data set using the previous two points.\n",
+ " next = model.predict(next_input)\n",
+ " # Append just the number of the predicted data set\n",
+ " y_pred.append(next[0][0])\n",
+ " # Create the input that will be used to predict the next data point in the data set.\n",
+ " next_input = np.array([[last, next[0]]], dtype=np.float64)\n",
+ " last = next\n",
+ "\n",
+ " # Print the mean squared error between the known data set and the predicted data set.\n",
+ " print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n",
+ " # Save the predicted data set as a csv file for later use\n",
+ " name = datatype + 'Predicted'+str(dim)+'.csv'\n",
+ " np.savetxt(name, y_pred, delimiter=',')\n",
+ " # Plot the known data set and the predicted data set. The red box represents the region that was used\n",
+ " # for the training data.\n",
+ " fig, ax = plt.subplots()\n",
+ " ax.plot(x1, y_test, label=\"true\", linewidth=3)\n",
+ " ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
+ " ax.legend()\n",
+ " # Created a red region to represent the points used in the training data.\n",
+ " ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n",
+ " plt.show()\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "model = rnn(length_of_sequences = rnn_input.shape[1])\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other Things to Try\n",
+ "\n",
+ "\n",
+ "Changing the size of the recurrent neural network and its parameters\n",
+ "can drastically change the results you get from the model. The below\n",
+ "code takes the simple recurrent neural network from above and adds a\n",
+ "second hidden layer, changes the number of neurons in the hidden\n",
+ "layer, and explicitly declares the activation function of the hidden\n",
+ "layers to be a sigmoid function. The loss function and optimizer can\n",
+ "also be changed but are kept the same as the above network. These\n",
+ "parameters can be tuned to provide the optimal result from the\n",
+ "network. For some ideas on how to improve the performance of a\n",
+ "[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons in the input and output layers\n",
+ " in_out_neurons = 1\n",
+ " # Number of neurons in the hidden layer, increased from the first network\n",
+ " hidden_neurons = 500\n",
+ " # Define the input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n",
+ " # function to be the sigmoid function (the default value is hyperbolic tangent)\n",
+ " rnn1 = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=True, # This needs to be True if another hidden layer is to follow\n",
+ " stateful = stateful, activation = 'sigmoid',\n",
+ " name=\"RNN1\")(inp)\n",
+ " rnn2 = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=False, activation = 'sigmoid',\n",
+ " stateful = stateful,\n",
+ " name=\"RNN2\")(rnn1)\n",
+ " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
+ " #and add it to the network immediately after the hidden layer.\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n",
+ " # Create the machine learning model starting with the input layer and ending with the \n",
+ " # output layer\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the machine learning model using the mean squared error function as the loss \n",
+ " # function and an Adams optimizer.\n",
+ " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
+ " return model\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "model = rnn_2layers(length_of_sequences = 2)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other Types of Recurrent Neural Networks\n",
+ "\n",
+ "Besides a simple recurrent neural network layer, there are two other\n",
+ "commonly used types of recurrent neural network layers: Long Short\n",
+ "Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n",
+ "introduction to these layers see \n",
+ "and .\n",
+ "\n",
+ "The first network created below is similar to the previous network,\n",
+ "but it replaces the SimpleRNN layers with LSTM layers. The second\n",
+ "network below has two hidden layers made up of GRUs, which are\n",
+ "preceeded by two dense (feeddorward) neural network layers. These\n",
+ "dense layers \"preprocess\" the data before it reaches the recurrent\n",
+ "layers. This architecture has been shown to improve the performance\n",
+ "of recurrent neural networks (see the link above and also\n",
+ "."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n",
+ " in_out_neurons = 1\n",
+ " hidden_neurons = 250\n",
+ " # Input Layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n",
+ " rnn= LSTM(hidden_neurons, \n",
+ " return_sequences=True,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\", use_bias=True, activation='tanh')(inp)\n",
+ " rnn1 = LSTM(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n",
+ " # Output layer\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n",
+ " # Define the midel\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the model\n",
+ " model.compile(loss='mean_squared_error', optimizer='adam') \n",
+ " # Return the model\n",
+ " return model\n",
+ "\n",
+ "def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n",
+ " two GRU layers) and returns the model.\n",
+ " \"\"\" \n",
+ " # Number of neurons on the input/output layers and hidden layers\n",
+ " in_out_neurons = 1\n",
+ " hidden_neurons = 250\n",
+ " # Input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Hidden Dense (feedforward) layers\n",
+ " dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n",
+ " dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n",
+ " # Hidden GRU layers\n",
+ " rnn1 = GRU(hidden_neurons, \n",
+ " return_sequences=True,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN1\", use_bias=True)(dnn1)\n",
+ " rnn = GRU(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\", use_bias=True)(rnn1)\n",
+ " # Output layer\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
+ " # Define the model\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the mdoel\n",
+ " model.compile(loss='mean_squared_error', optimizer='adam') \n",
+ " # Return the model\n",
+ " return model\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "# Change the method name to reflect which network you want to use\n",
+ "model = dnn2_gru2(length_of_sequences = 2)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)\n",
+ "\n",
+ "\n",
+ "# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n",
+ "# \n",
+ "# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "# Reshape the data for Keras specifications\n",
+ "X_train = X_train.reshape((dim, 1))\n",
+ "y_train = y_train.reshape((dim, 1))\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "# Set the sequence length to 1 for regular data formatting \n",
+ "model = rnn(length_of_sequences = 1)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict the remaining data points\n",
+ "X_pred = X_tot[dim:]\n",
+ "X_pred = X_pred.reshape((len(X_pred), 1))\n",
+ "y_model = model.predict(X_pred)\n",
+ "y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n",
+ "\n",
+ "# Plot the known data set and the predicted data set. The red box represents the region that was used\n",
+ "# for the training data.\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n",
+ "ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
+ "ax.legend()\n",
+ "# Created a red region to represent the points used in the training data.\n",
+ "ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n",
+ "plt.show()\n",
+ "\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/doc/src/LectureNotes/_build/html/chapter1.html b/doc/src/LectureNotes/_build/html/chapter1.html
index 46441256c..4455a060b 100644
--- a/doc/src/LectureNotes/_build/html/chapter1.html
+++ b/doc/src/LectureNotes/_build/html/chapter1.html
@@ -119,6 +119,11 @@
7. Dimensionality Reduction
+
@@ -1751,13 +1756,13 @@ but now splitting the data into a training set and a test set.
Training R2
-0.9999886705644145
+0.9999854211447763
Training MSE
-3.90943518299982
+6.298065171189058
Test R2
-0.9999697792755088
+0.9999855160996954
Test MSE
-25.32441051671905
+7.1872710004915445
@@ -1888,7 +1893,7 @@ dtype: int64
-
<matplotlib.axes._subplots.AxesSubplot at 0x7fb5be1db040>
+
<matplotlib.axes._subplots.AxesSubplot at 0x7f9dd7c37eb0>
Feature max values before scaling:
+Feature max values before scaling:
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1.]
Test set accuracy scaled data with Min-Max scaling: 0.97
@@ -679,7 +683,9 @@ Test set accuracy scaled data with Standar Scaler: 0.96
Test set accuracy: 0.95
-Test set accuracy scaled data: 0.96
+
+
+
Test set accuracy scaled data: 0.96
/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
@@ -947,10 +953,10 @@ covariance matrix through the np.linalg.eig() function.
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter3.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter3.html
index 45cae9446..26cb92774 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter3.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter3.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter4.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter4.html
index e15eb5827..5a8a0e5a1 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter4.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter4.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter5.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter5.html
index d66630259..335a300c2 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter5.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter5.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter6.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter6.html
index 7c190a792..71426d615 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter6.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter6.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter7.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter7.html
index 409ae0789..135392f9b 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter7.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/chapter7.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/lecturenotes/lecturenotes/notebooks.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/lecturenotes/lecturenotes/notebooks.html
index 3253a021c..5d794f596 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/lecturenotes/lecturenotes/notebooks.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/lecturenotes/lecturenotes/notebooks.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/notebooks.html b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/notebooks.html
index f388fed80..7962b9748 100644
--- a/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/notebooks.html
+++ b/doc/src/LectureNotes/_build/html/testbook/_build/jupyter_execute/notebooks.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter1.html b/doc/src/LectureNotes/_build/html/testbook/chapter1.html
index 193a8de3c..ccae0322d 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter1.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter1.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter2.html b/doc/src/LectureNotes/_build/html/testbook/chapter2.html
index 1f78bb349..0b6aa8244 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter2.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter2.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter3.html b/doc/src/LectureNotes/_build/html/testbook/chapter3.html
index ca795115c..927ff395d 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter3.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter3.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter4.html b/doc/src/LectureNotes/_build/html/testbook/chapter4.html
index cbc1e8217..0801201a6 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter4.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter4.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter5.html b/doc/src/LectureNotes/_build/html/testbook/chapter5.html
index 74c05c336..901060374 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter5.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter5.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter6.html b/doc/src/LectureNotes/_build/html/testbook/chapter6.html
index e48c39d7d..5df638df7 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter6.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter6.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/chapter7.html b/doc/src/LectureNotes/_build/html/testbook/chapter7.html
index 2aac939e8..acdf58c52 100644
--- a/doc/src/LectureNotes/_build/html/testbook/chapter7.html
+++ b/doc/src/LectureNotes/_build/html/testbook/chapter7.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/content.html b/doc/src/LectureNotes/_build/html/testbook/content.html
index d3596a040..8b3bcc931 100644
--- a/doc/src/LectureNotes/_build/html/testbook/content.html
+++ b/doc/src/LectureNotes/_build/html/testbook/content.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/intro.html b/doc/src/LectureNotes/_build/html/testbook/intro.html
index 679fa8fb5..4ebb9e5bc 100644
--- a/doc/src/LectureNotes/_build/html/testbook/intro.html
+++ b/doc/src/LectureNotes/_build/html/testbook/intro.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONDUCT.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONDUCT.html
index e82b3c2b7..59ba705a2 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONDUCT.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONDUCT.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONTRIBUTING.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONTRIBUTING.html
index a25bcd8f1..3b241a3d1 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONTRIBUTING.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/CONTRIBUTING.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/README.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/README.html
index c302f7bde..4189370a6 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/README.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/README.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/content.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/content.html
index 0c90c302f..5cbfd6ce8 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/content.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/content.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/intro.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/intro.html
index 7dab19a74..e7c7c7138 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/intro.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/intro.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/markdown.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/markdown.html
index a6b7b46e2..6f35fa6c4 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/markdown.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/markdown.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/notebooks.html b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/notebooks.html
index 79ecee8f8..2912b35e5 100644
--- a/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/notebooks.html
+++ b/doc/src/LectureNotes/_build/html/testbook/lecturenotes/lecturenotes/notebooks.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
diff --git a/doc/src/LectureNotes/_build/html/testbook/markdown.html b/doc/src/LectureNotes/_build/html/testbook/markdown.html
index 41e66e4e6..9432c7af8 100644
--- a/doc/src/LectureNotes/_build/html/testbook/markdown.html
+++ b/doc/src/LectureNotes/_build/html/testbook/markdown.html
@@ -88,99 +88,39 @@
1. Elements of Probability Theory and Statistical Data Analysis
-
\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## 3D volumes of neurons\n",
+ "\n",
+ "Convolutional Neural Networks take advantage of the fact that the\n",
+ "input consists of images and they constrain the architecture in a more\n",
+ "sensible way. \n",
+ "\n",
+ "In particular, unlike a regular Neural Network, the\n",
+ "layers of a CNN have neurons arranged in 3 dimensions: width,\n",
+ "height, depth. (Note that the word depth here refers to the third\n",
+ "dimension of an activation volume, not to the depth of a full Neural\n",
+ "Network, which can refer to the total number of layers in a network.)\n",
+ "\n",
+ "To understand it better, the above example of an image \n",
+ "with an input volume of\n",
+ "activations has dimensions $32\\times 32\\times 3$ (width, height,\n",
+ "depth respectively). \n",
+ "\n",
+ "The neurons in a layer will\n",
+ "only be connected to a small region of the layer before it, instead of\n",
+ "all of the neurons in a fully-connected manner. Moreover, the final\n",
+ "output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n",
+ "because by the\n",
+ "end of the CNN architecture we will reduce the full image into a\n",
+ "single vector of class scores, arranged along the depth\n",
+ "dimension. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "
A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Layers used to build CNNs\n",
+ "\n",
+ "\n",
+ "A simple CNN is a sequence of layers, and every layer of a CNN\n",
+ "transforms one volume of activations to another through a\n",
+ "differentiable function. We use three main types of layers to build\n",
+ "CNN architectures: Convolutional Layer, Pooling Layer, and\n",
+ "Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n",
+ "will stack these layers to form a full CNN architecture.\n",
+ "\n",
+ "A simple CNN for image classification could have the architecture:\n",
+ "\n",
+ "* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n",
+ "\n",
+ "* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n",
+ "\n",
+ "* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n",
+ "\n",
+ "* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n",
+ "\n",
+ "* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n",
+ "\n",
+ "## Transforming images\n",
+ "\n",
+ "CNNs transform the original image layer by layer from the original\n",
+ "pixel values to the final class scores. \n",
+ "\n",
+ "Observe that some layers contain\n",
+ "parameters and other don’t. In particular, the CNN layers perform\n",
+ "transformations that are a function of not only the activations in the\n",
+ "input volume, but also of the parameters (the weights and biases of\n",
+ "the neurons). On the other hand, the RELU/POOL layers will implement a\n",
+ "fixed function. The parameters in the CONV/FC layers will be trained\n",
+ "with gradient descent so that the class scores that the CNN computes\n",
+ "are consistent with the labels in the training set for each image.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## CNNs in brief\n",
+ "\n",
+ "In summary:\n",
+ "\n",
+ "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
+ "\n",
+ "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
+ "\n",
+ "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
+ "\n",
+ "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n",
+ "\n",
+ "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
+ "\n",
+ "For more material on convolutional networks, we strongly recommend\n",
+ "the course\n",
+ "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
+ "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
+ "\n",
+ "\n",
+ "As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
+ "to the network are 2D images. This is important because the number of features or pixels in images\n",
+ "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
+ "\n",
+ "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
+ "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
+ "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
+ "matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Setting it up\n",
+ "\n",
+ "It means that to represent the entire\n",
+ "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The MNIST dataset again\n",
+ "\n",
+ "The MNIST dataset consists of grayscale images with a pixel size of\n",
+ "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
+ "neuron in the first hidden layer.\n",
+ "\n",
+ "If we were to analyze images of size $128\\times 128$ we would require\n",
+ "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
+ "dealing with color images, as most images are, we have an image matrix\n",
+ "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
+ "meaning 3 times the number of weights $= 49152$ are required for every\n",
+ "single neuron in the first hidden layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Strong correlations\n",
+ "\n",
+ "Images typically have strong local correlations, meaning that a small\n",
+ "part of the image varies little from its neighboring regions. If for\n",
+ "example we have an image of a blue car, we can roughly assume that a\n",
+ "small blue part of the image is surrounded by other blue regions.\n",
+ "\n",
+ "Therefore, instead of connecting every single pixel to a neuron in the\n",
+ "first hidden layer, as we have previously done with deep neural\n",
+ "networks, we can instead connect each neuron to a small part of the\n",
+ "image (in all 3 RGB depth dimensions). The size of each small area is\n",
+ "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Layers of a CNN\n",
+ "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
+ "The input image is typically a square matrix of depth 3. \n",
+ "\n",
+ "A **convolution** is performed on the image which outputs\n",
+ "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
+ "\n",
+ "\n",
+ "Each filter slides along the input image, taking the dot product\n",
+ "between each small part of the image and the filter, in all depth\n",
+ "dimensions. This is then passed through a non-linear function,\n",
+ "typically the **Rectified Linear (ReLu)** function, which serves as the\n",
+ "activation of the neurons in the first convolutional layer. This is\n",
+ "further passed through a **pooling layer**, which reduces the size of the\n",
+ "convolutional layer, e.g. by taking the maximum or average across some\n",
+ "small regions, and this serves as input to the next convolutional\n",
+ "layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Systematic reduction\n",
+ "\n",
+ "By systematically reducing the size of the input volume, through\n",
+ "convolution and pooling, the network should create representations of\n",
+ "small parts of the input, and then from them assemble representations\n",
+ "of larger areas. The final pooling layer is flattened to serve as\n",
+ "input to a hidden layer, such that each neuron in the final pooling\n",
+ "layer is connected to every single neuron in the hidden layer. This\n",
+ "then serves as input to the output layer, e.g. a softmax output for\n",
+ "classification.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Prerequisites: Collect and pre-process data"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "inputs = (n_inputs, pixel_width, pixel_height, depth) = (1797, 8, 8, 1)\n",
+ "labels = (n_inputs) = (1797,)\n"
+ ]
+ },
+ {
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAqwAAACRCAYAAAAGuepqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAALD0lEQVR4nO3dX2jl6VkH8OdpZ6HWP3O6KKJ2d6ItFbYXmxtRsTJnQBAESWBZEaw7GWnBK2eW6o0gyUi9EC82I17o1Wa6ghUtJKCLIDqJ1lW0sBnozYKUtGux2MqeuKsiWl8vTgbDMH+yz++cnDcznw8EMnvy/J73l/Oc93zPLyfZbK0FAAD06j2LXgAAADyIwAoAQNcEVgAAuiawAgDQNYEVAICuCawAAHTtkQ+smbmbmZ847VrOFnPCSZkVTsqscBLm5GTOTGDNzIPM/IlFr+N+curTmfnVzDw8GqKPLnpdj5szMCe/m5nvHPv4r8x8e9HrehyZFU7qDMzKz2bmG0fPPf+SmTcz8zsWva7HjTmZrzMTWM+A5yPiFyLixyPiyYj424h4ZaErojuttV9srX3bnY+I+IOI+KNFr4v+mBXehb+JiB9rrZ2PiB+IiHMR8enFLokOnek5OfOBNTM/kJl/kplfz8y3jj7/4F1f9qHM/PujVxU7mfnksfofyczXMnOSmbczc1xcyvdHxOdba19qrX0zIn4/Ip4pHosZ62hOjq/pWyPiuYi4OfRYzI5Z4aR6mZXW2puttW8c+0/fjIgPV47F7JmT2TjzgTWm5/ByRFyIiKcj4j8j4nfu+poXYnr183sj4n8i4rcjIjLz+yLiT2P6CuPJiPjliPhcZn7X3U0y8+mjYXn6Puv4bER8ODM/kplPRMTliPizgefG7PQyJ8c9FxFfj4i/qpwQc2NWOKluZiUzP5aZhxHxdkznZXPYqTFD5mQGznxgba39a2vtc621/2itvR0RvxERF+/6sldaa19srf17RPxaRPxMZr43Ij4eEa+21l5trf1va+3PI+ILEfFT9+jzldbaqLX2lfss5Z8j4q8j4o2YDuPzEfHiTE6SwTqak+MuR8RnWmtt0MkxU2aFk+ppVlprnz/6Ue8HI+K3IuJgJifJYOZkNs58YM3M92fm72XmlzPz32J6BWJ0dEff8eaxz78cEU9ExHfG9NXO80evSCaZOYmIj0XE9xSWsh4RPxQRT0XE+yLiekT8ZWa+v3AsZqyjObmznqdiumF9pnoM5sOscFK9zUpERGvtqzH96d5nhxyH2TEns3Fu0QuYgU9FxA9GxA+31r6WmcsR8XpE5LGveerY509HxH9HxDdiOiCvtNY+OYN1PBsRf9ha+6ejf29l5mZM38f6hRkcn2F6mZM7XoiI11prX5rhMZkNs8JJ9TYrd5yLiA/N4bjUmJMZOGtXWJ/IzPcd+zgXEd8e0x/BT47epLx+j7qPZ+YzR1c7fz0i/vjYL0b9dGb+ZGa+9+iY43u8Gfok/iGmr4K+OzPfk5k/H9NXSP9YOlOG6HlO7nghIrYG1DMbZoWT6nZWMvPnjt6/mJl5IaY/cv6L8pkyhDmZk7MWWF+N6Z1+52Mjpm8Y/paYvhL5u7j3Lzq9EtMN/2sx/XH9L0VMf2MuIlYi4ldj+gsNb0bEr8Q9vi9Hd/I7ef83M/9mRNyOiP2ImMT0/avPtdYm7/40GajnOYnM/NGYvn/InyhaPLPCSfU8K89ExGsR8U5M/3TRGxExjytyPJw5mZP0Hn4AAHp21q6wAgDwmBFYAQDomsAKAEDXBFYAALr2sL/Deuq/kbW1tVWq29jYKPccjUalus3N+v/RbDwel2sHyId/Sdmpz8ru7m6prjpjERHb29ulusPDw3LPW7duleoGzti8ZuXU52RnZ6dUd/Xq1Rmv5OGqMx0RsbS0NLN1vAvd7SkHBwflhtU9fcieUt0bzp8/X+65v79fqhs4Y13tKZNJ/Q/4LGJOquut3tcR/e0prrACANA1gRUAgK4JrAAAdE1gBQCgawIrAABdE1gBAOiawAoAQNcEVgAAuiawAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXTs3j4Pu7u6Wa69cuVKqW1lZKfccjUalutXV1XLPyWRSrmXq2rVrpboh3/u1tbVS3Y0bN8o9q/P5KDk4OCjXDnmcnrbt7e1ybfXx8KhZxPfh5s2b5dpbt26V6obsKZ5/hn0Pqo/TIXtRtefW1la558bGRrl2HlxhBQCgawIrAABdE1gBAOiawAoAQNcEVgAAuiawAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXRNYAQDomsAKAEDXBFYAALomsAIA0LVsrT3o9gfeeD/Xrl2rrSYiDg4OSnXb29vlnuPxuFQ3Go3KPYesd4Cc47FLszJEdVaG3G97e3ulusuXL5d7TiaTcu0A85qVU5+Tzc3NUt3y8nK556VLl0p1Fy9eLPfc3d0t1w7wSO0pi1B9vtzf3y/3fMRm5bGYk2pOGbKPVffOge47J66wAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXRNYAQDomsAKAEDXBFYAALomsAIA0DWBFQCArgmsAAB0TWAFAKBrAisAAF07N4+DLi0tlWsPDg5KdRsbG+Wee3t7pbrXX3+93JPhJpNJqa46YxER6+vrpbrRaFTuWV3vkMfho2Rtba1UN2RPqaruRRH19S7iPPl/y8vLpbqtra1yz+reOWQfe5RU9+TV1dXZLuQENjc3T73nvLjCCgBA1wRWAAC6JrACANA1gRUAgK4JrAAAdE1gBQCgawIrAABdE1gBAOiawAoAQNcEVgAAuiawAgDQNYEVAICuCawAAHRNYAUAoGvZWnvQ7Q+8cR6Wl5dLdbdv3y73vHz5cqlua2ur3HNBco7HLs3Kzs5OueHq6mq59ixZX18v1W1sbAxpO69ZKc3J/v5+ueF4PC7VHR4elntWVfeiiPr9vbS0VO4ZHe4pj4sh91t179zc3Cz3jM72lCGq+1F1L4qo70cvv/xyuefa2lq5doD7zokrrAAAdE1gBQCgawIrAABdE1gBAOiawAoAQNcEVgAAuiawAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXRNYAQDomsAKAEDXsrX2oNsfeOM8LC8vn3bLGI1Gpboha93c3CzXDpBzPHZpVnZ3d8sNt7e3S3X7+/vlngcHB6feszqfA81rVk59Ti5dulSurVpZWSnVVWd6gbrbUx4X4/H41HsOeRxGZ3vKZDKZ9ToeasheXr2/q89ZQ2sHuO+cuMIKAEDXBFYAALomsAIA0DWBFQCArgmsAAB0TWAFAKBrAisAAF0TWAEA6JrACgBA1wRWAAC6JrACANA1gRUAgK4JrAAAdE1gBQCga+cWvYC7jUajUt14PC733NjYKNVV17qonj0acr8dHh6W6ra2tso9V1dXS3WP2v122obMydWrV0t1N27cKPe8cuVKuZbF2dnZKdVduHCh3HN/f/9U6yLqzz+Pkr29vXLt+vp6qe769evlnmtra6W6IXvRZDIp1c3r+c4VVgAAuiawAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXRNYAQDomsAKAEDXBFYAALomsAIA0DWBFQCArgmsAAB0TWAFAKBr5xa9gLu9+OKLpbrV1dVyz+vXr5fqVlZWyj1Ho1G5lqm33nqrVHd4eFjuuba2Vq7lbHn22WfLtUP2BhbnpZdeKtXt7e2Ve54/f75UN2Qvso9FXLx4sVw7Ho9LddX5ioiYTCaluqtXr5Z79pZTXGEFAKBrAisAAF0TWAEA6JrACgBA1wRWAAC6JrACANA1gRUAgK4JrAAAdE1gBQCgawIrAABdE1gBAOiawAoAQNcEVgAAuiawAgDQtWytLXoNAABwX66wAgDQNYEVAICuCawAAHRNYAUAoGsCKwAAXRNYAQDo2v8BlXpliBTuHMEAAAAASUVORK5CYII=\n",
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {
+ "filenames": {
+ "image/png": "/Users/hjensen/Teaching/FYS-STK4150/doc/src/LectureNotes/_build/jupyter_execute/chapter9_3_1.png"
+ },
+ "needs_background": "light"
+ },
+ "output_type": "display_data"
+ }
+ ],
+ "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",
+ "# RGB images have a depth of 3\n",
+ "# our images are grayscale so they should have a depth of 1\n",
+ "inputs = inputs[:,:,:,np.newaxis]\n",
+ "\n",
+ "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
+ "print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
+ "\n",
+ "\n",
+ "# choose some random images to display\n",
+ "n_inputs = len(inputs)\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": [
+ "## Importing Keras and Tensorflow"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from tensorflow.keras import datasets, layers, models\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",
+ "#from tensorflow.keras import Conv2D\n",
+ "#from tensorflow.keras import MaxPooling2D\n",
+ "#from tensorflow.keras import Flatten\n",
+ "\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "\n",
+ "# representation of labels\n",
+ "labels = to_categorical(labels)\n",
+ "\n",
+ "# split into train and test data\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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Running with Keras"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
+ " n_filters, n_neurons_connected, n_categories,\n",
+ " eta, lmbd):\n",
+ " model = Sequential()\n",
+ " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
+ " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
+ " model.add(layers.Flatten())\n",
+ " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " \n",
+ " sgd = optimizers.SGD(lr=eta)\n",
+ " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
+ " \n",
+ " return model\n",
+ "\n",
+ "epochs = 100\n",
+ "batch_size = 100\n",
+ "input_shape = X_train.shape[1:4]\n",
+ "receptive_field = 3\n",
+ "n_filters = 10\n",
+ "n_neurons_connected = 50\n",
+ "n_categories = 10\n",
+ "\n",
+ "eta_vals = np.logspace(-5, 1, 7)\n",
+ "lmbd_vals = np.logspace(-5, 1, 7)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Final part"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 2.5817 - accuracy: 0.2500"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 917us/step - loss: 2.8078 - accuracy: 0.1139\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 1e-05\n",
+ "Test accuracy: 0.114\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 3.0782 - accuracy: 0.1875"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 932us/step - loss: 3.3640 - accuracy: 0.1500\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 0.0001\n",
+ "Test accuracy: 0.150\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 2.7005 - accuracy: 0.0312"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 933us/step - loss: 2.7588 - accuracy: 0.0944\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 0.001\n",
+ "Test accuracy: 0.094\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 3.9994 - accuracy: 0.1250"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 1ms/step - loss: 4.2041 - accuracy: 0.1028\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 0.01\n",
+ "Test accuracy: 0.103\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 12.9177 - accuracy: 0.1250"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 939us/step - loss: 12.8693 - accuracy: 0.1056\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 0.1\n",
+ "Test accuracy: 0.106\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 92.4325 - accuracy: 0.1250"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 2ms/step - loss: 92.4491 - accuracy: 0.1111\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 1.0\n",
+ "Test accuracy: 0.111\n",
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\r",
+ " 1/12 [=>............................] - ETA: 0s - loss: 514.5186 - accuracy: 0.0312"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r",
+ "12/12 [==============================] - 0s 939us/step - loss: 514.2589 - accuracy: 0.1028\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Learning rate = 1e-05\n",
+ "Lambda = 10.0\n",
+ "Test accuracy: 0.103\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "CNN_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",
+ " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
+ " n_filters, n_neurons_connected, n_categories,\n",
+ " eta, lmbd)\n",
+ " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
+ " scores = CNN.evaluate(X_test, Y_test)\n",
+ " \n",
+ " CNN_keras[i][j] = CNN\n",
+ " \n",
+ " print(\"Learning rate = \", eta)\n",
+ " print(\"Lambda = \", lmbd)\n",
+ " print(\"Test accuracy: %.3f\" % scores[1])\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Final visualization"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# 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",
+ " CNN = CNN_keras[i][j]\n",
+ "\n",
+ " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
+ " test_accuracy[i][j] = CNN.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 CIFAR01 data set\n",
+ "\n",
+ "The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n",
+ "6,000 images in each class. The dataset is divided into 50,000\n",
+ "training images and 10,000 testing images. The classes are mutually\n",
+ "exclusive and there is no overlap between them."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import tensorflow as tf\n",
+ "\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# We import the data set\n",
+ "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n",
+ "\n",
+ "# Normalize pixel values to be between 0 and 1 by dividing by 255. \n",
+ "train_images, test_images = train_images / 255.0, test_images / 255.0"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Verifying the data set\n",
+ "\n",
+ "To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
+ " 'dog', 'frog', 'horse', 'ship', 'truck']\n",
+ "\n",
+ "plt.figure(figsize=(10,10))\n",
+ "for i in range(25):\n",
+ " plt.subplot(5,5,i+1)\n",
+ " plt.xticks([])\n",
+ " plt.yticks([])\n",
+ " plt.grid(False)\n",
+ " plt.imshow(train_images[i], cmap=plt.cm.binary)\n",
+ " # The CIFAR labels happen to be arrays, \n",
+ " # which is why you need the extra index\n",
+ " plt.xlabel(class_names[train_labels[i][0]])\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Set up the model\n",
+ "\n",
+ "The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n",
+ "\n",
+ "As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model = models.Sequential()\n",
+ "model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n",
+ "model.add(layers.MaxPooling2D((2, 2)))\n",
+ "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
+ "model.add(layers.MaxPooling2D((2, 2)))\n",
+ "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
+ "\n",
+ "# Let's display the architecture of our model so far.\n",
+ "\n",
+ "model.summary()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Add Dense layers on top\n",
+ "\n",
+ "To complete our model, you will feed the last output tensor from the\n",
+ "convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n",
+ "to perform classification. Dense layers take vectors as input (which\n",
+ "are 1D), while the current output is a 3D tensor. First, you will\n",
+ "flatten (or unroll) the 3D output to 1D, then add one or more Dense\n",
+ "layers on top. CIFAR has 10 output classes, so you use a final Dense\n",
+ "layer with 10 outputs and a softmax activation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model.add(layers.Flatten())\n",
+ "model.add(layers.Dense(64, activation='relu'))\n",
+ "model.add(layers.Dense(10))\n",
+ "Here's the complete architecture of our model.\n",
+ "\n",
+ "model.summary()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.\n",
+ "\n",
+ "\n",
+ "## Compile and train the model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "model.compile(optimizer='adam',\n",
+ " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
+ " metrics=['accuracy'])\n",
+ "\n",
+ "history = model.fit(train_images, train_labels, epochs=10, \n",
+ " validation_data=(test_images, test_labels))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Finally, evaluate the model"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "plt.plot(history.history['accuracy'], label='accuracy')\n",
+ "plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n",
+ "plt.xlabel('Epoch')\n",
+ "plt.ylabel('Accuracy')\n",
+ "plt.ylim([0.5, 1])\n",
+ "plt.legend(loc='lower right')\n",
+ "\n",
+ "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n",
+ "\n",
+ "print(test_acc)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Recurrent neural networks: Overarching view\n",
+ "\n",
+ "Till now our focus has been, including convolutional neural networks\n",
+ "as well, on feedforward neural networks. The output or the activations\n",
+ "flow only in one direction, from the input layer to the output layer.\n",
+ "\n",
+ "A recurrent neural network (RNN) looks very much like a feedforward\n",
+ "neural network, except that it also has connections pointing\n",
+ "backward. \n",
+ "\n",
+ "RNNs are used to analyze time series data such as stock prices, and\n",
+ "tell you when to buy or sell. In autonomous driving systems, they can\n",
+ "anticipate car trajectories and help avoid accidents. More generally,\n",
+ "they can work on sequences of arbitrary lengths, rather than on\n",
+ "fixed-sized inputs like all the nets we have discussed so far. For\n",
+ "example, they can take sentences, documents, or audio samples as\n",
+ "input, making them extremely useful for natural language processing\n",
+ "systems such as automatic translation and speech-to-text.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Set up of an RNN\n",
+ "\n",
+ "\n",
+ "Text to come.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## A simple example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# Start importing packages\n",
+ "import pandas as pd\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import tensorflow as tf\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Model, Sequential \n",
+ "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
+ "from tensorflow.keras import optimizers \n",
+ "from tensorflow.keras import regularizers \n",
+ "from tensorflow.keras.utils import to_categorical \n",
+ "\n",
+ "\n",
+ "\n",
+ "# convert into dataset matrix\n",
+ "def convertToMatrix(data, step):\n",
+ " X, Y =[], []\n",
+ " for i in range(len(data)-step):\n",
+ " d=i+step \n",
+ " X.append(data[i:d,])\n",
+ " Y.append(data[d,])\n",
+ " return np.array(X), np.array(Y)\n",
+ "\n",
+ "step = 4\n",
+ "N = 1000 \n",
+ "Tp = 800 \n",
+ "\n",
+ "t=np.arange(0,N)\n",
+ "x=np.sin(0.02*t)+2*np.random.rand(N)\n",
+ "df = pd.DataFrame(x)\n",
+ "df.head()\n",
+ "\n",
+ "plt.plot(df)\n",
+ "plt.show()\n",
+ "\n",
+ "values=df.values\n",
+ "train,test = values[0:Tp,:], values[Tp:N,:]\n",
+ "\n",
+ "# add step elements into train and test\n",
+ "test = np.append(test,np.repeat(test[-1,],step))\n",
+ "train = np.append(train,np.repeat(train[-1,],step))\n",
+ " \n",
+ "trainX,trainY =convertToMatrix(train,step)\n",
+ "testX,testY =convertToMatrix(test,step)\n",
+ "trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
+ "testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
+ "\n",
+ "model = Sequential()\n",
+ "model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
+ "model.add(Dense(8, activation=\"relu\")) \n",
+ "model.add(Dense(1))\n",
+ "model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
+ "model.summary()\n",
+ "\n",
+ "model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
+ "trainPredict = model.predict(trainX)\n",
+ "testPredict= model.predict(testX)\n",
+ "predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
+ "\n",
+ "trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
+ "print(trainScore)\n",
+ "\n",
+ "index = df.index.values\n",
+ "plt.plot(index,df)\n",
+ "plt.plot(index,predicted)\n",
+ "plt.axvline(df.index[Tp], c=\"r\")\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## An extrapolation example\n",
+ "\n",
+ "The following code provides an example of how recurrent neural\n",
+ "networks can be used to extrapolate to unknown values of physics data\n",
+ "sets. Specifically, the data sets used in this program come from\n",
+ "a quantum mechanical many-body calculation of energies as functions of the number of particles."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "# For matrices and calculations\n",
+ "import numpy as np\n",
+ "# For machine learning (backend for keras)\n",
+ "import tensorflow as tf\n",
+ "# User-friendly machine learning library\n",
+ "# Front end for TensorFlow\n",
+ "import tensorflow.keras\n",
+ "# Different methods from Keras needed to create an RNN\n",
+ "# This is not necessary but it shortened function calls \n",
+ "# that need to be used in the code.\n",
+ "from tensorflow.keras import datasets, layers, models\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras import regularizers\n",
+ "from tensorflow.keras.models import Model, Sequential\n",
+ "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
+ "# For timing the code\n",
+ "from timeit import default_timer as timer\n",
+ "# For plotting\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "\n",
+ "# The data set\n",
+ "datatype='VaryDimension'\n",
+ "X_tot = np.arange(2, 42, 2)\n",
+ "y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n",
+ "\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n",
+ "\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Formatting the Data\n",
+ "\n",
+ "The way the recurrent neural networks are trained in this program\n",
+ "differs from how machine learning algorithms are usually trained.\n",
+ "Typically a machine learning algorithm is trained by learning the\n",
+ "relationship between the x data and the y data. In this program, the\n",
+ "recurrent neural network will be trained to recognize the relationship\n",
+ "in a sequence of y values. This is type of data formatting is\n",
+ "typically used time series forcasting, but it can also be used in any\n",
+ "extrapolation (time series forecasting is just a specific type of\n",
+ "extrapolation along the time axis). This method of data formatting\n",
+ "does not use the x data and assumes that the y data are evenly spaced.\n",
+ "\n",
+ "For a standard machine learning algorithm, the training data has the\n",
+ "form of (x,y) so the machine learning algorithm learns to assiciate a\n",
+ "y value with a given x value. This is useful when the test data has x\n",
+ "values within the same range as the training data. However, for this\n",
+ "application, the x values of the test data are outside of the x values\n",
+ "of the training data and the traditional method of training a machine\n",
+ "learning algorithm does not work as well. For this reason, the\n",
+ "recurrent neural network is trained on sequences of y values of the\n",
+ "form ((y1, y2), y3), so that the network is concerned with learning\n",
+ "the pattern of the y data and not the relation between the x and y\n",
+ "data. As long as the pattern of y data outside of the training region\n",
+ "stays relatively stable compared to what was inside the training\n",
+ "region, this method of training can produce accurate extrapolations to\n",
+ "y values far removed from the training data set.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# FORMAT_DATA\n",
+ "def format_data(data, length_of_sequence = 2): \n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " data(a numpy array): the data that will be the inputs to the recurrent neural\n",
+ " network\n",
+ " length_of_sequence (an int): the number of elements in one iteration of the\n",
+ " sequence patter. For a function approximator use length_of_sequence = 2.\n",
+ " Returns:\n",
+ " rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n",
+ " dimensions are length of data - length of sequence, length of sequence, \n",
+ " dimnsion of data\n",
+ " rnn_output (a numpy array): the training data for the neural network\n",
+ " Formats data to be used in a recurrent neural network.\n",
+ " \"\"\"\n",
+ "\n",
+ " X, Y = [], []\n",
+ " for i in range(len(data)-length_of_sequence):\n",
+ " # Get the next length_of_sequence elements\n",
+ " a = data[i:i+length_of_sequence]\n",
+ " # Get the element that immediately follows that\n",
+ " b = data[i+length_of_sequence]\n",
+ " # Reshape so that each data point is contained in its own array\n",
+ " a = np.reshape (a, (len(a), 1))\n",
+ " X.append(a)\n",
+ " Y.append(b)\n",
+ " rnn_input = np.array(X)\n",
+ " rnn_output = np.array(Y)\n",
+ "\n",
+ " return rnn_input, rnn_output\n",
+ "\n",
+ "\n",
+ "# ## Defining the Recurrent Neural Network Using Keras\n",
+ "# \n",
+ "# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n",
+ "\n",
+ "def rnn(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons in the input and output layers\n",
+ " in_out_neurons = 1\n",
+ " # Number of neurons in the hidden layer\n",
+ " hidden_neurons = 200\n",
+ " # Define the input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n",
+ " # the network immediately after the input layer\n",
+ " rnn = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\")(inp)\n",
+ " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
+ " #and add it to the network immediately after the hidden layer.\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
+ " # Create the machine learning model starting with the input layer and ending with the \n",
+ " # output layer\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the machine learning model using the mean squared error function as the loss \n",
+ " # function and an Adams optimizer.\n",
+ " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
+ " return model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Predicting New Points With A Trained Recurrent Neural Network"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def test_rnn (x1, y_test, plot_min, plot_max):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " x1 (a list or numpy array): The complete x component of the data set\n",
+ " y_test (a list or numpy array): The complete y component of the data set\n",
+ " plot_min (an int or float): the smallest x value used in the training data\n",
+ " plot_max (an int or float): the largest x valye used in the training data\n",
+ " Returns:\n",
+ " None.\n",
+ " Uses a trained recurrent neural network model to predict future points in the \n",
+ " series. Computes the MSE of the predicted data set from the true data set, saves\n",
+ " the predicted data set to a csv file, and plots the predicted and true data sets w\n",
+ " while also displaying the data range used for training.\n",
+ " \"\"\"\n",
+ " # Add the training data as the first dim points in the predicted data array as these\n",
+ " # are known values.\n",
+ " y_pred = y_test[:dim].tolist()\n",
+ " # Generate the first input to the trained recurrent neural network using the last two \n",
+ " # points of the training data. Based on how the network was trained this means that it\n",
+ " # will predict the first point in the data set after the training data. All of the \n",
+ " # brackets are necessary for Tensorflow.\n",
+ " next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n",
+ " # Save the very last point in the training data set. This will be used later.\n",
+ " last = [y_test[dim-1]]\n",
+ "\n",
+ " # Iterate until the complete data set is created.\n",
+ " for i in range (dim, len(y_test)):\n",
+ " # Predict the next point in the data set using the previous two points.\n",
+ " next = model.predict(next_input)\n",
+ " # Append just the number of the predicted data set\n",
+ " y_pred.append(next[0][0])\n",
+ " # Create the input that will be used to predict the next data point in the data set.\n",
+ " next_input = np.array([[last, next[0]]], dtype=np.float64)\n",
+ " last = next\n",
+ "\n",
+ " # Print the mean squared error between the known data set and the predicted data set.\n",
+ " print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n",
+ " # Save the predicted data set as a csv file for later use\n",
+ " name = datatype + 'Predicted'+str(dim)+'.csv'\n",
+ " np.savetxt(name, y_pred, delimiter=',')\n",
+ " # Plot the known data set and the predicted data set. The red box represents the region that was used\n",
+ " # for the training data.\n",
+ " fig, ax = plt.subplots()\n",
+ " ax.plot(x1, y_test, label=\"true\", linewidth=3)\n",
+ " ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
+ " ax.legend()\n",
+ " # Created a red region to represent the points used in the training data.\n",
+ " ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n",
+ " plt.show()\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "model = rnn(length_of_sequences = rnn_input.shape[1])\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other Things to Try\n",
+ "\n",
+ "\n",
+ "Changing the size of the recurrent neural network and its parameters\n",
+ "can drastically change the results you get from the model. The below\n",
+ "code takes the simple recurrent neural network from above and adds a\n",
+ "second hidden layer, changes the number of neurons in the hidden\n",
+ "layer, and explicitly declares the activation function of the hidden\n",
+ "layers to be a sigmoid function. The loss function and optimizer can\n",
+ "also be changed but are kept the same as the above network. These\n",
+ "parameters can be tuned to provide the optimal result from the\n",
+ "network. For some ideas on how to improve the performance of a\n",
+ "[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons in the input and output layers\n",
+ " in_out_neurons = 1\n",
+ " # Number of neurons in the hidden layer, increased from the first network\n",
+ " hidden_neurons = 500\n",
+ " # Define the input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n",
+ " # function to be the sigmoid function (the default value is hyperbolic tangent)\n",
+ " rnn1 = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=True, # This needs to be True if another hidden layer is to follow\n",
+ " stateful = stateful, activation = 'sigmoid',\n",
+ " name=\"RNN1\")(inp)\n",
+ " rnn2 = SimpleRNN(hidden_neurons, \n",
+ " return_sequences=False, activation = 'sigmoid',\n",
+ " stateful = stateful,\n",
+ " name=\"RNN2\")(rnn1)\n",
+ " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
+ " #and add it to the network immediately after the hidden layer.\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n",
+ " # Create the machine learning model starting with the input layer and ending with the \n",
+ " # output layer\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the machine learning model using the mean squared error function as the loss \n",
+ " # function and an Adams optimizer.\n",
+ " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
+ " return model\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "model = rnn_2layers(length_of_sequences = 2)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Other Types of Recurrent Neural Networks\n",
+ "\n",
+ "Besides a simple recurrent neural network layer, there are two other\n",
+ "commonly used types of recurrent neural network layers: Long Short\n",
+ "Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n",
+ "introduction to these layers see \n",
+ "and .\n",
+ "\n",
+ "The first network created below is similar to the previous network,\n",
+ "but it replaces the SimpleRNN layers with LSTM layers. The second\n",
+ "network below has two hidden layers made up of GRUs, which are\n",
+ "preceeded by two dense (feeddorward) neural network layers. These\n",
+ "dense layers \"preprocess\" the data before it reaches the recurrent\n",
+ "layers. This architecture has been shown to improve the performance\n",
+ "of recurrent neural networks (see the link above and also\n",
+ "."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n",
+ " \"\"\"\n",
+ " # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n",
+ " in_out_neurons = 1\n",
+ " hidden_neurons = 250\n",
+ " # Input Layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n",
+ " rnn= LSTM(hidden_neurons, \n",
+ " return_sequences=True,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\", use_bias=True, activation='tanh')(inp)\n",
+ " rnn1 = LSTM(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n",
+ " # Output layer\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n",
+ " # Define the midel\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the model\n",
+ " model.compile(loss='mean_squared_error', optimizer='adam') \n",
+ " # Return the model\n",
+ " return model\n",
+ "\n",
+ "def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n",
+ " \"\"\"\n",
+ " Inputs:\n",
+ " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
+ " when the data is formatted\n",
+ " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
+ " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
+ " Returns:\n",
+ " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
+ " method\n",
+ " Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n",
+ " two GRU layers) and returns the model.\n",
+ " \"\"\" \n",
+ " # Number of neurons on the input/output layers and hidden layers\n",
+ " in_out_neurons = 1\n",
+ " hidden_neurons = 250\n",
+ " # Input layer\n",
+ " inp = Input(batch_shape=(batch_size, \n",
+ " length_of_sequences, \n",
+ " in_out_neurons)) \n",
+ " # Hidden Dense (feedforward) layers\n",
+ " dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n",
+ " dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n",
+ " # Hidden GRU layers\n",
+ " rnn1 = GRU(hidden_neurons, \n",
+ " return_sequences=True,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN1\", use_bias=True)(dnn1)\n",
+ " rnn = GRU(hidden_neurons, \n",
+ " return_sequences=False,\n",
+ " stateful = stateful,\n",
+ " name=\"RNN\", use_bias=True)(rnn1)\n",
+ " # Output layer\n",
+ " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
+ " # Define the model\n",
+ " model = Model(inputs=[inp],outputs=[dens])\n",
+ " # Compile the mdoel\n",
+ " model.compile(loss='mean_squared_error', optimizer='adam') \n",
+ " # Return the model\n",
+ " return model\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "\n",
+ "# Generate the training data for the RNN, using a sequence of 2\n",
+ "rnn_input, rnn_training = format_data(y_train, 2)\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "# Change the method name to reflect which network you want to use\n",
+ "model = dnn2_gru2(length_of_sequences = 2)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict more points of the data set\n",
+ "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)\n",
+ "\n",
+ "\n",
+ "# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n",
+ "# \n",
+ "# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n",
+ "\n",
+ "# Check to make sure the data set is complete\n",
+ "assert len(X_tot) == len(y_tot)\n",
+ "\n",
+ "# This is the number of points that will be used in as the training data\n",
+ "dim=12\n",
+ "\n",
+ "# Separate the training data from the whole data set\n",
+ "X_train = X_tot[:dim]\n",
+ "y_train = y_tot[:dim]\n",
+ "\n",
+ "# Reshape the data for Keras specifications\n",
+ "X_train = X_train.reshape((dim, 1))\n",
+ "y_train = y_train.reshape((dim, 1))\n",
+ "\n",
+ "\n",
+ "# Create a recurrent neural network in Keras and produce a summary of the \n",
+ "# machine learning model\n",
+ "# Set the sequence length to 1 for regular data formatting \n",
+ "model = rnn(length_of_sequences = 1)\n",
+ "model.summary()\n",
+ "\n",
+ "# Start the timer. Want to time training+testing\n",
+ "start = timer()\n",
+ "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
+ "# validation split. Setting verbose to True prints information about each training iteration.\n",
+ "hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n",
+ " verbose=True,validation_split=0.05)\n",
+ "\n",
+ "\n",
+ "# This section plots the training loss and the validation loss as a function of training iteration.\n",
+ "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
+ "# being overtrained.\n",
+ "for label in [\"loss\",\"val_loss\"]:\n",
+ " plt.plot(hist.history[label],label=label)\n",
+ "\n",
+ "plt.ylabel(\"loss\")\n",
+ "plt.xlabel(\"epoch\")\n",
+ "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
+ "plt.legend()\n",
+ "plt.show()\n",
+ "\n",
+ "# Use the trained neural network to predict the remaining data points\n",
+ "X_pred = X_tot[dim:]\n",
+ "X_pred = X_pred.reshape((len(X_pred), 1))\n",
+ "y_model = model.predict(X_pred)\n",
+ "y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n",
+ "\n",
+ "# Plot the known data set and the predicted data set. The red box represents the region that was used\n",
+ "# for the training data.\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n",
+ "ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
+ "ax.legend()\n",
+ "# Created a red region to represent the points used in the training data.\n",
+ "ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n",
+ "plt.show()\n",
+ "\n",
+ "# Stop the timer and calculate the total time needed.\n",
+ "end = timer()\n",
+ "print('Time: ', end-start)"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
\ No newline at end of file
diff --git a/doc/src/LectureNotes/_build/jupyter_execute/chapter9.py b/doc/src/LectureNotes/_build/jupyter_execute/chapter9.py
new file mode 100644
index 000000000..3964ccd20
--- /dev/null
+++ b/doc/src/LectureNotes/_build/jupyter_execute/chapter9.py
@@ -0,0 +1,1185 @@
+# Convolutional Neural Networks
+
+
+Convolutional neural networks (CNNs) were developed during the last
+decade of the previous century, with a focus on character recognition
+tasks. Nowadays, CNNs are a central element in the spectacular success
+of deep learning methods. The success in for example image
+classifications have made them a central tool for most machine
+learning practitioners.
+
+CNNs are very similar to ordinary Neural Networks.
+They are made up of neurons that have learnable weights and
+biases. Each neuron receives some inputs, performs a dot product and
+optionally follows it with a non-linearity. The whole network still
+expresses a single differentiable score function: from the raw image
+pixels on one end to class scores at the other. And they still have a
+loss function (for example Softmax) on the last (fully-connected) layer
+and all the tips/tricks we developed for learning regular Neural
+Networks still apply (back propagation, gradient descent etc etc).
+
+What is the difference? **CNN architectures make the explicit assumption that
+the inputs are images, which allows us to encode certain properties
+into the architecture. These then make the forward function more
+efficient to implement and vastly reduce the amount of parameters in
+the network.**
+
+Here we provide only a superficial overview, for the more interested, we recommend highly the course
+[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)
+and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).
+
+Another good read is the article here .
+
+
+
+
+
+## Neural Networks vs CNNs
+
+Neural networks are defined as **affine transformations**, that is
+a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
+output (to which a bias vector is usually added before passing the result
+through a nonlinear activation function). This is applicable to any type of input, be it an
+image, a sound clip or an unordered collection of features: whatever their
+dimensionality, their representation can always be flattened into a vector
+before the transformation.
+
+
+
+## Why CNNS for images, sound files, medical images from CT scans etc?
+
+However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
+structure. More formally, they share these important properties:
+* They are stored as multi-dimensional arrays (think of the pixels of a figure) .
+
+* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).
+
+* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).
+
+These properties are not exploited when an affine transformation is applied; in
+fact, all the axes are treated in the same way and the topological information
+is not taken into account. Still, taking advantage of the implicit structure of
+the data may prove very handy in solving some tasks, like computer vision and
+speech recognition, and in these cases it would be best to preserve it. This is
+where discrete convolutions come into play.
+
+A discrete convolution is a linear transformation that preserves this notion of
+ordering. It is sparse (only a few input units contribute to a given output
+unit) and reuses parameters (the same weights are applied to multiple locations
+in the input).
+
+
+
+
+
+## Regular NNs don’t scale well to full images
+
+As an example, consider
+an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
+single fully-connected neuron in a first hidden layer of a regular
+Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
+seems manageable, but clearly this fully-connected structure does not
+scale to larger images. For example, an image of more respectable
+size, say $200\times 200\times 3$, would lead to neurons that have
+$200\times 200\times 3 = 120,000$ weights.
+
+We could have
+several such neurons, and the parameters would add up quickly! Clearly,
+this full connectivity is wasteful and the huge number of parameters
+would quickly lead to possible overfitting.
+
+
+
+
+
A regular 3-layer Neural Network.
+
+
+
+
+
+
+## 3D volumes of neurons
+
+Convolutional Neural Networks take advantage of the fact that the
+input consists of images and they constrain the architecture in a more
+sensible way.
+
+In particular, unlike a regular Neural Network, the
+layers of a CNN have neurons arranged in 3 dimensions: width,
+height, depth. (Note that the word depth here refers to the third
+dimension of an activation volume, not to the depth of a full Neural
+Network, which can refer to the total number of layers in a network.)
+
+To understand it better, the above example of an image
+with an input volume of
+activations has dimensions $32\times 32\times 3$ (width, height,
+depth respectively).
+
+The neurons in a layer will
+only be connected to a small region of the layer before it, instead of
+all of the neurons in a fully-connected manner. Moreover, the final
+output layer could for this specific image have dimensions $1\times 1 \times 10$,
+because by the
+end of the CNN architecture we will reduce the full image into a
+single vector of class scores, arranged along the depth
+dimension.
+
+
+
+
+
A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).