diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 025808c71..86e4a7cdd 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -1,31 +1,28 @@
- + -
- - - -
-
- -
-
+
@@ -470,33 +429,22 @@ MathJax.Hub.Config({
- - -
- +
-
- +
-We start here with the most basic algorithm, the so-called decision +
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, +
Decision trees are supervised learning algorithms used for both, classification and regression tasks. +
--The main idea of decision trees +
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 +
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. +where we then finally end up in so called leaf nodes. +
-
-
- +
-A decision tree is typically divided into a root node, the interior 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 +
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. +
-
-
- +

-

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.
--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. - -
-
- +
-The overarching approach to decision trees is a top-down approach. +
The overarching approach to decision trees is a top-down approach.
This process is then repeated for the subtree rooted at the new node. +
-
-
- +
-In simplified terms, the process of training a decision tree and +
In simplified terms, the process of training a decision tree and predicting the target features of query instances is as follows: +
Then we are essentially done!
-Then we are essentially done! - -
-
- - -
+
import numpy as np
+
+
+
+
+
+ import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
@@ -513,8 +482,22 @@ plt.ylabel(&quo
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-
- +
-There are mainly two steps - +
There are mainly two steps
How do we construct the regions \( R_1,\dots,R_J \)? In theory, the regions could have any shape. However, we choose to divide the predictor space into high-dimensional rectangles, or boxes, for simplicity and for ease of interpretation of the resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the MSE, given by +
$$ \sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, $$ --where \( \overline{y}_{R_j} \) is the mean response for the training observations -within box \( j \). +
where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). +
-
-
- +
-Unfortunately, it is computationally infeasible to consider every +
Unfortunately, it is computationally infeasible to consider every possible partition of the feature space into \( J \) boxes. The common strategy is to take a top-down approach +
--The approach is top-down because it begins at the top of the tree (all +
The approach is top-down because it begins at the top of the tree (all observations belong to a single region) and then successively splits the predictor space; each split is indicated via two new branches further down on the tree. It is greedy because at each step of the tree-building process, the best split is made at that particular step, rather than looking ahead and picking a split that will lead to a better tree in some future step. +
-
-
- +
-In order to implement the recursive binary splitting we start by selecting +
In order to implement the recursive binary splitting we start by selecting the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +
$$ \left\{X\vert x_j < s\right\}, $$ -and +and
$$ \left\{X\vert x_j \geq s\right\}, $$ -so that we obtain the lowest MSE, that is +so that we obtain the lowest MSE, that is
$$ \sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, $$ --which we want to minimize by considering all predictors +
which we want to minimize by considering all predictors \( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value. +
--For any \( j \) and \( s \), we define the pair of half-planes where +
For any \( j \) and \( s \), we define the pair of half-planes where \( \overline{y}_{R_1} \) is the mean response for the training observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean response for the training observations in \( R_2(j,s) \). +
--Finding the values of \( j \) and \( s \) that minimize the above equation can be +
Finding the values of \( j \) and \( s \) that minimize the above equation can be done quite quickly, especially when the number of features \( p \) is not too large. +
--Next, we repeat the process, looking +
Next, we repeat the process, looking for the best predictor and best cutpoint in order to split the data further so as to minimize the MSE within each of the resulting regions. However, this time, instead of splitting the entire predictor @@ -468,8 +432,8 @@ have three regions. Again, we look to split one of these three regions further, so as to minimize the MSE. The process continues until a stopping criterion is reached; for instance, we may continue until no region contains more than five observations. +
-
-
- +
-The above procedure is rather straightforward, but leads often to +
The above procedure is rather straightforward, but leads often to overfitting and unnecessarily large and complicated trees. The basic idea is to grow a large tree \( T_0 \) and then prune it back in order to obtain a subtree. A smaller tree with fewer splits (fewer regions) can lead to smaller variance and better interpretation at the cost of a little more bias. +
--The so-called Cost complexity pruning algorithm gives us a +
The so-called Cost complexity pruning algorithm gives us a way to do just this. Rather than considering every possible subtree, we consider a sequence of trees indexed by a nonnegative tuning parameter \( \alpha \). +
--Read more at the following Scikit-Learn link on pruning. +
Read more at the following Scikit-Learn link on pruning.
-
-
- +
-For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +
For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
$$ \sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, $$ -is as small as possible. Here \( \overline{T} \) is +is as small as possible. Here \( \overline{T} \) is the number of terminal nodes of the tree \( T \) , \( R_m \) is the rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. +
--The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +
The tuning parameter \( \alpha \) controls a trade-off between the subtree’s complexity and its fit to the training data. When \( \alpha = 0 \), then the subtree \( T \) will simply equal \( T_0 \), because then the above equation just measures the training error. However, as \( \alpha \) increases, there is a price to pay for having a tree with many terminal nodes. The above equation will -tend to be minimized for a smaller subtree. +tend to be minimized for a smaller subtree. +
--It turns out that as we increase \( \alpha \) from zero +
It turns out that as we increase \( \alpha \) from zero branches get pruned from the tree in a nested and predictable fashion, so obtaining the whole sequence of subtrees as a function of \( \alpha \) is easy. We can select a value of \( \alpha \) using a validation set or using cross-validation. We then return to the full data set and obtain the -subtree corresponding to \( \alpha \). +subtree corresponding to \( \alpha \). +
-
-
- +
+
-
- +
-A classification tree is very similar to a regression tree, except +
A classification tree is very similar to a regression tree, except that it is used to predict a qualitative response rather than a quantitative one. Recall that for a regression tree, the predicted response for an observation is given by the mean response of the @@ -435,9 +399,9 @@ in the region to which it belongs. In interpreting the results of a classification tree, we are often interested not only in the class prediction corresponding to a particular terminal node region, but also in the class proportions among the training observations that -fall into that region. +fall into that region. +
-
-
- +
-The task of growing a +
The task of growing a classification tree is quite similar to the task of growing a regression tree. Just as in the regression setting, we use recursive binary splitting to grow a classification tree. However, in the @@ -434,15 +398,15 @@ error rate. Since we plan to assign an observation in a given region to the most commonly occurring error rate class of training observations in that region, the classification error rate is simply the fraction of the training observations in that region that do not -belong to the most common class. +belong to the most common class. +
--When building a classification tree, either the Gini index or the +
When building a classification tree, either the Gini index or the entropy are typically used to evaluate the quality of a particular split, since these two approaches are more sensitive to node purity -than is the classification error rate. +than is the classification error rate. +
-
-
- +
-If our targets are the outcome of a classification process that takes +
If our targets are the outcome of a classification process that takes for example \( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node. +
--We define a PDF \( p_{mk} \) that represents the number of observations of +
We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as +
$$ p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). $$ --We let \( p_{mk} \) represent the majority class of observations in region +
We let \( p_{mk} \) represent the majority class of observations in region \( m \). The three most common ways of splitting a node are given by +
+
-
- -<<<<<<< HEAD -
The Gini index \( g \) gives us the degree of probability of a specific variable that is wrongly classified. @@ -435,48 +400,6 @@ variable that is wrongly classified.
It favors binary splitting.
-======= - -- - -
import os
-from sklearn.datasets import load_breast_cancer
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.metrics import confusion_matrix
-from sklearn.tree import export_graphviz
-
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import pandas as pd
-import numpy as np
-
-
-cancer = load_breast_cancer()
-X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-print(X)
-y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
-y = pd.get_dummies(y)
-print(y)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
-tree_clf = DecisionTreeClassifier(max_depth=5)
-tree_clf.fit(X_train, y_train)
-
-export_graphviz(
- tree_clf,
- out_file="DataFiles/cancer.dot",
- feature_names=cancer.feature_names,
- class_names=cancer.target_names,
- rounded=True,
- filled=True
-)
-cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
-os.system(cmd)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
It is custom to split to a tree uising binary splits. The reason is that multiway splits fragment the data too quickly, leaving @@ -429,39 +394,6 @@ insufficient data at the next level down. Multiway splits can be achieved by a series of binary split and this is normally preferred.
-======= - -- - -
# Common imports
-import numpy as np
-from sklearn.model_selection import train_test_split
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.datasets import make_moons
-from sklearn.tree import export_graphviz
-from pydot import graph_from_dot_data
-import pandas as pd
-import os
-
-np.random.seed(42)
-X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
-X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
-tree_clf = DecisionTreeClassifier(max_depth=5)
-tree_clf.fit(X_train, y_train)
-
-export_graphviz(
- tree_clf,
- out_file="DataFiles/moons.dot",
- rounded=True,
- filled=True
-)
-cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
-os.system(cmd)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
import os
-from sklearn.datasets import load_breast_cancer
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.metrics import confusion_matrix
-from sklearn.tree import export_graphviz
+Consider the following example with attributes/features and two
+possible outcomes (classes) for each attribute. Assume we wish to find some
+correlations between the average grade of a student as function of the
+number of hours studied and hours slept. We want also to correlate the
+grade in a given course with the general trend, whether the students
+recently has gotten grades below average or above.
+
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import pandas as pd
-import numpy as np
-
-
-cancer = load_breast_cancer()
-X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-print(X)
-y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
-y = pd.get_dummies(y)
-print(y)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
-tree_clf = DecisionTreeClassifier(max_depth=5)
-tree_clf.fit(X_train, y_train)
-
-export_graphviz(
- tree_clf,
- out_file="DataFiles/cancer.dot",
- feature_names=cancer.feature_names,
- class_names=cancer.target_names,
- rounded=True,
- filled=True
-)
-cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
-os.system(cmd)
-
--Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. - -
- - -
from sklearn.datasets import load_iris
-from sklearn import tree
-X, y = load_iris(return_X_y=True)
-tree_clf = tree.DecisionTreeClassifier()
-tree_clf = tree_clf.fit(X, y)
-# and then plot the tree
-tree.plot_tree(tree_clf)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +
We have three features/attributes
+-
- -<<<<<<< HEAD -
# Common imports
-import numpy as np
-from sklearn.model_selection import train_test_split
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.datasets import make_moons
-from sklearn.tree import export_graphviz
-from pydot import graph_from_dot_data
-import pandas as pd
-import os
+
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+
+
+
+
+
+
-np.random.seed(42)
-X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
-X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
-tree_clf = DecisionTreeClassifier(max_depth=5)
-tree_clf.fit(X_train, y_train)
-
-export_graphviz(
- tree_clf,
- out_file="DataFiles/moons.dot",
- rounded=True,
- filled=True
-)
-cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
-os.system(cmd)
-
--Alternatively, the tree can also be exported in textual format with the function exporttext. -This method doesn’t require the installation of external libraries and is more compact: - -
- - -
from sklearn.datasets import load_iris
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.tree import export_text
-iris = load_iris()
-decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
-decision_tree = decision_tree.fit(iris.data, iris.target)
-r = export_text(decision_tree, feature_names=iris['feature_names'])
-print(r)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.
+In computations we will translate all classes into numbers. Being +these binary classes, they can easily be split into ones and zeros. +
+ +from sklearn.datasets import load_iris
-from sklearn import tree
-X, y = load_iris(return_X_y=True)
-tree_clf = tree.DecisionTreeClassifier()
-tree_clf = tree_clf.fit(X, y)
-# and then plot the tree
-tree.plot_tree(tree_clf)
-
-Two algorithms stand out in the set up of decision trees: - -
-
- -<<<<<<< HEAD -
Alternatively, the tree can also be exported in textual format with the function exporttext. -This method doesn’t require the installation of external libraries and is more compact: -
+from sklearn.datasets import load_iris
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.tree import export_text
-iris = load_iris()
-decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
-decision_tree = decision_tree.fit(iris.data, iris.target)
-r = export_text(decision_tree, feature_names=iris['feature_names'])
-print(r)
-
-For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). -This could be for example a threshold set by a number below a certain circumference of a malign tumor. - -
-How do we find these two quantities? -We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). -The cost function it tries to minimize is then -$$ -C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, -$$ - -where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) - is the number of instances in the left/right subset - -
-Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets -and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the -\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other -hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), -\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
Two algorithms stand out in the set up of decision trees:
-We discuss both algorithms with applications here. The popular library -Scikit-Learn uses the CART algorithm. For classification problems -you can use either the gini index or the entropy to split a tree -in two branches. -
-======= +-The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the -training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now -$$ -C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. -$$ +
-Without any regularization, the regression task for decision trees, -just like for classification tasks, is prone to overfitting. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). -This could be for example a threshold set by a number below a certain circumference of a malign tumor. -
+ +import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
-How do we find these two quantities?
-We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \).
-The cost function it tries to minimize is then
-
-$$
-C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
-$$
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
-where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
- is the number of instances in the left/right subset
-
-Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
-and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the
-\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other
-hyperparameters control additional stopping conditions such as the \( min\_samples\_split \),
-\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).
-
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
-=======
+export_graphviz(
+ tree_clf,
+ out_file="DataFiles/cancer.dot",
+ feature_names=cancer.feature_names,
+ class_names=cancer.target_names,
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+-The example we will look at is a classical one in many Machine -Learning applications. Based on various meteorological features, we -have several so-called attributes which decide whether we at the end -will do some outdoor activity like skiing, going for a bike ride etc -etc. The table here contains the feautures outlook, temperature, -humidity and wind. The target or output is whether we ride -(True=1) or whether we do something else that day (False=0). The -attributes for each feature are then sunny, overcast and rain for the -outlook, hot, cold and mild for temperature, high and normal for -humidity and weak and strong for wind. - -
-The table here summarizes the various attributes and - -
| Day | Outlook | Temperature | Humidity | Wind | Ride |
| 1 | Sunny | Hot | High | Weak | 0 |
| 2 | Sunny | Hot | High | Strong | 1 |
| 3 | Overcast | Hot | High | Weak | 1 |
| 4 | Rain | Mild | High | Weak | 1 |
| 5 | Rain | Cool | Normal | Weak | 1 |
| 6 | Rain | Cool | Normal | Strong | 0 |
| 7 | Overcast | Cool | Normal | Strong | 1 |
| 8 | Sunny | Mild | High | Weak | 0 |
| 9 | Sunny | Cool | Normal | Weak | 1 |
| 10 | Rain | Mild | Normal | Weak | 1 |
| 11 | Sunny | Mild | Normal | Strong | 1 |
| 12 | Overcast | Mild | High | Strong | 1 |
| 13 | Overcast | Hot | Normal | Weak | 1 |
| 14 | Rain | Mild | High | Strong | 0 |
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
+
# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
from sklearn.tree import export_graphviz
-from sklearn.preprocessing import StandardScaler, OneHotEncoder
-from sklearn.compose import ColumnTransformer
-from IPython.display import Image
from pydot import graph_from_dot_data
+import pandas as pd
import os
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
-training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now
-
-$$
-C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
-$$
-
-Here the MSE for a specific node is defined as
-$$
-\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
-$$
-
-with
-$$
-\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
-$$
-
-<<<<<<< HEAD
-the mean value of all observations in a specific node.
-
-Without any regularization, the regression task for decision trees,
-just like for classification tasks, is prone to overfitting.
-
-
-=======
-infile = open(data_path("rideclass.csv"),'r')
-
-# Read the experimental data with Pandas
-from IPython.display import display
-ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
-ridedata = pd.DataFrame(ridedata)
-
-# Features and targets
-X = ridedata.loc[:, ridedata.columns != 'Ride'].values
-y = ridedata.loc[:, ridedata.columns == 'Ride'].values
-
-# Create the encoder.
-encoder = OneHotEncoder(handle_unknown="ignore")
-# Assume for simplicity all features are categorical.
-encoder.fit(X)
-# Apply the encoder.
-X = encoder.transform(X)
-print(X)
-# Then do a Classification tree
-tree_clf = DecisionTreeClassifier(max_depth=2)
-tree_clf.fit(X, y)
-print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
-#transfer to a decision tree graph
export_graphviz(
tree_clf,
- out_file="DataFiles/ride.dot",
+ out_file="DataFiles/moons.dot",
rounded=True,
filled=True
)
-cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
os.system(cmd)
-
-
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+
+
+
+
+
+
+
+
+
+
+
+
+-
- -<<<<<<< HEAD -
The example we will look at is a classical one in many Machine -Learning applications. Based on various meteorological features, we -have several so-called attributes which decide whether we at the end -will do some outdoor activity like skiing, going for a bike ride etc -etc. The table here contains the feautures outlook, temperature, -humidity and wind. The target or output is whether we ride -(True=1) or whether we do something else that day (False=0). The -attributes for each feature are then sunny, overcast and rain for the -outlook, hot, cold and mild for temperature, high and normal for -humidity and weak and strong for wind. -
+Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.
-The table here summarizes the various attributes and
-| Day | Outlook | Temperature | Humidity | Wind | Ride |
| 1 | Sunny | Hot | High | Weak | 0 |
| 2 | Sunny | Hot | High | Strong | 1 |
| 3 | Overcast | Hot | High | Weak | 1 |
| 4 | Rain | Mild | High | Weak | 1 |
| 5 | Rain | Cool | Normal | Weak | 1 |
| 6 | Rain | Cool | Normal | Strong | 0 |
| 7 | Overcast | Cool | Normal | Strong | 1 |
| 8 | Sunny | Mild | High | Weak | 0 |
| 9 | Sunny | Cool | Normal | Weak | 1 |
| 10 | Rain | Mild | Normal | Weak | 1 |
| 11 | Sunny | Mild | Normal | Strong | 1 |
| 12 | Overcast | Mild | High | Strong | 1 |
| 13 | Overcast | Hot | Normal | Weak | 1 |
| 14 | Rain | Mild | High | Strong | 0 |
-The above functions (gini, entropy and misclassification error) are -important components of the so-called CART algorithm. We will discuss -this algorithm below after we have discussed the information gain -algorithm ID3. - -
-In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. - -
-
# Split a dataset based on an attribute and an attribute value
-def test_split(index, value, dataset):
- left, right = list(), list()
- for row in dataset:
- if row[index] < value:
- left.append(row)
- else:
- right.append(row)
- return left, right
-
-# Calculate the Gini index for a split dataset
-def gini_index(groups, classes):
- # count all samples at split point
- n_instances = float(sum([len(group) for group in groups]))
- # sum weighted Gini index for each group
- gini = 0.0
- for group in groups:
- size = float(len(group))
- # avoid divide by zero
- if size == 0:
- continue
- score = 0.0
- # score the group based on the score for each class
- for class_val in classes:
- p = [row[-1] for row in group].count(class_val) / size
- score += p * p
- # weight the group score by its relative size
- gini += (1.0 - score) * (size / n_instances)
- return gini
+
+
+
+
+
+ from sklearn.datasets import load_iris
+from sklearn import tree
+X, y = load_iris(return_X_y=True)
+tree_clf = tree.DecisionTreeClassifier()
+tree_clf = tree_clf.fit(X, y)
+# and then plot the tree
+tree.plot_tree(tree_clf)
+
+
+
+
+
+
+
+
+
+
+
+
+
-# Select the best split point for a dataset
-def get_split(dataset):
- class_values = list(set(row[-1] for row in dataset))
- b_index, b_value, b_score, b_groups = 999, 999, 999, None
- for index in range(len(dataset[0])-1):
- for row in dataset:
- groups = test_split(index, row[index], dataset)
- gini = gini_index(groups, class_values)
- print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
- if gini < b_score:
- b_index, b_value, b_score, b_groups = index, row[index], gini, groups
- return {'index':b_index, 'value':b_value, 'groups':b_groups}
-
-dataset = [[0,0,0,0,0],
- [0,0,0,1,1],
- [1,0,0,0,1],
- [2,1,0,0,1],
- [2,2,1,0,1],
- [2,2,1,1,0],
- [1,2,1,1,1],
- [0,1,0,0,0],
- [0,2,1,0,1],
- [2,1,1,0,1],
- [0,1,1,1,1],
- [1,1,0,1,1],
- [1,0,1,0,1],
- [2,1,0,1,0]]
-split = get_split(dataset)
-print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
Alternatively, the tree can also be exported in textual format with the function exporttext. +This method doesn’t require the installation of external libraries and is more compact: +
@@ -430,73 +399,14 @@ MathJax.Hub.Config({# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
+ from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.tree import export_graphviz
-from sklearn.preprocessing import StandardScaler, OneHotEncoder
-from sklearn.compose import ColumnTransformer
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("rideclass.csv"),'r')
-
-# Read the experimental data with Pandas
-from IPython.display import display
-ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
-ridedata = pd.DataFrame(ridedata)
-
-# Features and targets
-X = ridedata.loc[:, ridedata.columns != 'Ride'].values
-y = ridedata.loc[:, ridedata.columns == 'Ride'].values
-
-# Create the encoder.
-encoder = OneHotEncoder(handle_unknown="ignore")
-# Assume for simplicity all features are categorical.
-encoder.fit(X)
-# Apply the encoder.
-X = encoder.transform(X)
-print(X)
-# Then do a Classification tree
-tree_clf = DecisionTreeClassifier(max_depth=2)
-tree_clf.fit(X, y)
-print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
-#transfer to a decision tree graph
-export_graphviz(
- tree_clf,
- out_file="DataFiles/ride.dot",
- rounded=True,
- filled=True
-)
-cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
-os.system(cmd)
+from sklearn.tree import export_text
+iris = load_iris()
+decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
+decision_tree = decision_tree.fit(iris.data, iris.target)
+r = export_text(decision_tree, feature_names=iris['feature_names'])
+print(r)
-The ID3 algorithm learns decision trees by constructing -them in a top down way, beginning with the question which attribute should be tested at the root of the tree? - -
-We would like to select the attribute that is most useful for classifying -examples. - -
-What is a good quantitative measure of the worth of an attribute? - -
-Information gain measures how well a given attribute separates the -training examples according to their target classification. - -
-The ID3 algorithm uses this information gain measure to select among the candidate -attributes at each step while growing the tree. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
- -<<<<<<< HEAD -
The above functions (gini, entropy and misclassification error) are -important components of the so-called CART algorithm. We will discuss -this algorithm below after we have discussed the information gain -algorithm ID3. +
Two algorithms stand out in the set up of decision trees:
+We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches.
-In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.
- - - -# Split a dataset based on an attribute and an attribute value
-def test_split(index, value, dataset):
- left, right = list(), list()
- for row in dataset:
- if row[index] < value:
- left.append(row)
- else:
- right.append(row)
- return left, right
-
-# Calculate the Gini index for a split dataset
-def gini_index(groups, classes):
- # count all samples at split point
- n_instances = float(sum([len(group) for group in groups]))
- # sum weighted Gini index for each group
- gini = 0.0
- for group in groups:
- size = float(len(group))
- # avoid divide by zero
- if size == 0:
- continue
- score = 0.0
- # score the group based on the score for each class
- for class_val in classes:
- p = [row[-1] for row in group].count(class_val) / size
- score += p * p
- # weight the group score by its relative size
- gini += (1.0 - score) * (size / n_instances)
- return gini
-=======
-
-Cancer Data again now with Decision Trees and other Methods
-
-
-
-
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
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-# Select the best split point for a dataset
-def get_split(dataset):
- class_values = list(set(row[-1] for row in dataset))
- b_index, b_value, b_score, b_groups = 999, 999, 999, None
- for index in range(len(dataset[0])-1):
- for row in dataset:
- groups = test_split(index, row[index], dataset)
- gini = gini_index(groups, class_values)
- print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
- if gini < b_score:
- b_index, b_value, b_score, b_groups = index, row[index], gini, groups
- return {'index':b_index, 'value':b_value, 'groups':b_groups}
-
-dataset = [[0,0,0,0,0],
- [0,0,0,1,1],
- [1,0,0,0,1],
- [2,1,0,0,1],
- [2,2,1,0,1],
- [2,2,1,1,0],
- [1,2,1,1,1],
- [0,1,0,0,0],
- [0,2,1,0,1],
- [2,1,1,0,1],
- [0,1,1,1,1],
- [1,1,0,1,1],
- [1,0,1,0,1],
- [2,1,0,1,0]]
-
-<<<<<<< HEAD
-split = get_split(dataset)
-print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
-
-
- ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
- - -
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
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-The ID3 algorithm learns decision trees by constructing
-them in a top down way, beginning with the question which attribute should be tested at the root of the tree?
+
For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \).
+This could be for example a threshold set by a number below a certain circumference of a malign tumor.
-
-- Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
-- The best attribute is selected and used as the test at the root node of the tree.
-- A descendant of the root node is then created for each possible value of this attribute.
-- Training examples are sorted to the appropriate descendant node.
-- The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
-- This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
-
-The ID3 algorithm selects which attribute to test at each node in the
-tree.
+
How do we find these two quantities?
+We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \).
+The cost function it tries to minimize is then
+
+$$
+C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
+$$
+
+where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
+ is the number of instances in the left/right subset
-We would like to select the attribute that is most useful for classifying
-examples.
+
Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
+and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the
+\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other
+hyperparameters control additional stopping conditions such as the \( min\_samples\_split \),
+\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).
-What is a good quantitative measure of the worth of an attribute?
-
-Information gain measures how well a given attribute separates the
-training examples according to their target classification.
-
-
-<<<<<<< HEAD
-The ID3 algorithm uses this information gain measure to select among the candidate
-attributes at each step while growing the tree.
-
-
-=======
-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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
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
-=======
+The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
+training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now
+
+$$
+C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
+$$
-Playing around with regions
-
+
Here the MSE for a specific node is defined as
+$$
+\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
+$$
-
-np.random.seed(6)
-Xs = np.random.rand(100, 2) - 0.5
-ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+with
+$$
+\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
+$$
-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)
+the mean value of all observations in a specific node.
-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)
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+Without any regularization, the regression task for decision trees,
+just like for classification tasks, is prone to overfitting.
+
-# Load the data
-cancer = load_breast_cancer()
-
-<<<<<<< HEAD
-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)))
-
-
- ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
from __future__ import division, print_function, unicode_literals
+The example we will look at is a classical one in many Machine
+Learning applications. Based on various meteorological features, we
+have several so-called attributes which decide whether we at the end
+will do some outdoor activity like skiing, going for a bike ride etc
+etc. The table here contains the feautures outlook, temperature,
+humidity and wind. The target or output is whether we ride
+(True=1) or whether we do something else that day (False=0). The
+attributes for each feature are then sunny, overcast and rain for the
+outlook, hot, cold and mild for temperature, high and normal for
+humidity and weak and strong for wind.
+
-# Common imports
-import numpy as np
-import os
+The table here summarizes the various attributes and
+
+
+
+
+Day Outlook Temperature Humidity Wind Ride
+
+
+ 1 Sunny Hot High Weak 0
+ 2 Sunny Hot High Strong 1
+ 3 Overcast Hot High Weak 1
+ 4 Rain Mild High Weak 1
+ 5 Rain Cool Normal Weak 1
+ 6 Rain Cool Normal Strong 0
+ 7 Overcast Cool Normal Strong 1
+ 8 Sunny Mild High Weak 0
+ 9 Sunny Cool Normal Weak 1
+ 10 Rain Mild Normal Weak 1
+ 11 Sunny Mild Normal Strong 1
+ 12 Overcast Mild High Strong 1
+ 13 Overcast Hot Normal Weak 1
+ 14 Rain Mild High Strong 0
+
+
+
+
-# 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()
-
-- - -
# 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
-- - -
from sklearn.tree import DecisionTreeRegressor
-
-tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
-tree_reg.fit(X, y)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
np.random.seed(6)
-Xs = np.random.rand(100, 2) - 0.5
-ys = (Xs[:, 0] > 0).astype(np.float32) * 2
-=======
+ # Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import os
-Final regressor code
-
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-
-
from sklearn.tree import DecisionTreeRegressor
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-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)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-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)
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-plt.figure(figsize=(11, 4))
-plt.subplot(121)
-<<<<<<< HEAD
-plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
-=======
-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)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
-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)
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
-plt.show()
-
-
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-
-
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)
+infile = open(data_path("rideclass.csv"),'r')
-x1 = np.linspace(0, 1, 500).reshape(-1, 1)
-y_pred1 = tree_reg1.predict(x1)
-y_pred2 = tree_reg2.predict(x1)
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
-plt.figure(figsize=(11, 4))
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
-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)
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+ tree_clf,
+ out_file="DataFiles/ride.dot",
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+
+
- -<<<<<<< HEAD -
The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. +
+ +In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.
+# 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
-
-from sklearn.tree import DecisionTreeRegressor
+ # Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+ left, right = list(), list()
+ for row in dataset:
+ if row[index] < value:
+ left.append(row)
+ else:
+ right.append(row)
+ return left, right
+
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+ # count all samples at split point
+ n_instances = float(sum([len(group) for group in groups]))
+ # sum weighted Gini index for each group
+ gini = 0.0
+ for group in groups:
+ size = float(len(group))
+ # avoid divide by zero
+ if size == 0:
+ continue
+ score = 0.0
+ # score the group based on the score for each class
+ for class_val in classes:
+ p = [row[-1] for row in group].count(class_val) / size
+ score += p * p
+ # weight the group score by its relative size
+ gini += (1.0 - score) * (size / n_instances)
+ return gini
-tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
-tree_reg.fit(X, y)
+# Select the best split point for a dataset
+def get_split(dataset):
+ class_values = list(set(row[-1] for row in dataset))
+ b_index, b_value, b_score, b_groups = 999, 999, 999, None
+ for index in range(len(dataset[0])-1):
+ for row in dataset:
+ groups = test_split(index, row[index], dataset)
+ gini = gini_index(groups, class_values)
+ print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+ if gini < b_score:
+ b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+ return {'index':b_index, 'value':b_value, 'groups':b_groups}
+
+dataset = [[0,0,0,0,0],
+ [0,0,0,1,1],
+ [1,0,0,0,1],
+ [2,1,0,0,1],
+ [2,2,1,0,1],
+ [2,2,1,1,0],
+ [1,2,1,1,1],
+ [0,1,0,0,0],
+ [0,2,1,0,1],
+ [2,1,1,0,1],
+ [0,1,1,1,1],
+ [1,1,0,1,1],
+ [1,0,1,0,1],
+ [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
-
- -<<<<<<< HEAD -
from sklearn.tree import DecisionTreeRegressor
+The ID3 algorithm learns decision trees by constructing
+them in a top down way, beginning with the question which attribute should be tested at the root of the tree?
+
-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)
+
+- Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
+- The best attribute is selected and used as the test at the root node of the tree.
+- A descendant of the root node is then created for each possible value of this attribute.
+- Training examples are sorted to the appropriate descendant node.
+- The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
+- This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
+
+The ID3 algorithm selects which attribute to test at each node in the
+tree.
+
-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}$")
+We would like to select the attribute that is most useful for classifying
+examples.
+
-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)
+What is a good quantitative measure of the worth of an attribute?
-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)
+Information gain measures how well a given attribute separates the
+training examples according to their target classification.
+
-plt.show()
-
-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)
+The ID3 algorithm uses this information gain measure to select among the candidate
+attributes at each step while growing the tree.
+
-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()
-
-
-
- -<<<<<<< HEAD -
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
-
-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?
+# Load the data
+cancer = load_breast_cancer()
-
-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
+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)))
+
+
-
- -<<<<<<< HEAD -
However, by aggregating many decision trees, using methods like -bagging, random forests, and boosting, the predictive performance of -trees can be substantially improved. -
-======= + +from __future__ import division, print_function, unicode_literals
-An Overview of Ensemble Methods
+# 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()
+
+
-

-
- -<<<<<<< HEAD -
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? -
+ +np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
-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
-
-=======
+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)
-Bagging
+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)
-
-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.
+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)
-
-Bootstrap aggregation, or just bagging, is a
-general-purpose procedure for reducing the variance of a statistical
-learning method.
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+plt.show()
+
+We discuss these methods here.
-
-
- -<<<<<<< HEAD -

# 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
+
+from sklearn.tree import DecisionTreeRegressor
-More bagging
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+-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. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
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. -
-======= - --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 \)). -
+
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
+
+
+
+
+
+ from sklearn.tree import DecisionTreeRegressor
-n = 1000
-n_boostraps = 100
-maxdepth = 10
+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)
-# 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)
+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}$")
-# we produce a simple tree first as benchmark, no scaling
-simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train, y_train)
-simpleprediction = simpletree.predict(X_test)
-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, y_train)
- model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test)#.ravel()
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+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)
- 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))
-print(mse_simpletree)
-plt.xlim(1,maxdepth)
-plt.plot(polydegree, error, label='MSE')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-save_fig("baggingboot")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 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()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
- -<<<<<<< HEAD -
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. -
-======= - --The idea behind boosting, and voting as well can be phrased as follows: -Can a group of people somehow arrive at highly -reasoned decisions, despite the weak judgement of the individual -members? - -
-The aim is to create a good classifier by combining several weak classifiers. -A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. - -
-The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. -In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in -each iteration. - -
-Decision trees play an important role as our weak classifier. They serve as the basic method. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
+
-
- -<<<<<<< HEAD -
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()
-
-However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. +
--The simplest case is a so-called voting ensemble. To illustrate this, -think of yourself tossing coins with a biased outcome of 51 per cent -for heads and 49% for tails. With only few tosses, -you may not clearly see this distribution for heads and tails. However, after some -thousands of tosses, there will be a clear majority of heads. With 2000 tosses -you should see approximately 1020 heads and 980 tails. - -
-We can then state that the outcome is a clear majority of heads. If -you do this ten thousand times, it is easy to see that there is a 97% -likelihood of a majority of heads. - -
-Another example would be to collect all polls before an -election. Different polls may show different likelihoods for a -candidate winning with say a majority of the popular vote. The majority vote -would then consist in many polls indicating that this candidate will -actually win. - -
-The example here shows how we can implement the coin tossing case, -clealry demostrating that after some tosses we see the law of large -numbers kicking in. - -
-
- -<<<<<<< HEAD -
from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
+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?
+
-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)
+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
+
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
+
+- Voting classifiers
+- Bagging and Pasting
+- Random forests
+- Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+
+We discuss these methods here.
-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))
-
-- - -
# Common imports
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.tree import export_graphviz
-from sklearn.preprocessing import StandardScaler, OneHotEncoder
-from sklearn.compose import ColumnTransformer
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-
- -<<<<<<< HEAD -

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)
-
-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(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)
-
-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))
-
-- - -
# Common imports
-import numpy as np
-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
-
-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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
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. +
- -from sklearn.ensemble import BaggingClassifier
-from sklearn.tree import DecisionTreeClassifier
+Bootstrap aggregation, or just bagging, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
-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)
-
-from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-
-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))
-
-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()
-
--We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn. -
- - -
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
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-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))
-
-
- -<<<<<<< HEAD -
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 \)). +
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.
- -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
+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.
+
-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)
-print(mse_simpletree)
-plt.xlim(1,maxdepth)
-plt.plot(polydegree, error, label='MSE')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-save_fig("baggingboot")
-plt.show()
-
-- - -
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)
-- - -
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(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)
-- - -
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))
-
-
- -<<<<<<< HEAD -
The idea behind boosting, and voting as well can be phrased as follows: -Can a group of people somehow arrive at highly -reasoned decisions, despite the weak judgement of the individual -members? +
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 \)).
-The aim is to create a good classifier by combining several weak classifiers. -A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. -
+ +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
-The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
-In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in
-each iteration.
-
+n = 1000
+n_boostraps = 100
+maxdepth = 10
-Decision trees play an important role as our weak classifier. They serve as the basic method.
-=======
+# 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)
-Random forests
+# we produce a simple tree first as benchmark, no scaling
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
+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, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test)#.ravel()
-
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
+ 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))
+print(mse_simpletree)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+-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 - -$$ -m\approx \sqrt{p}. -$$ ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-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. - -
-
- -<<<<<<< HEAD -
The simplest case is a so-called voting ensemble. To illustrate this, -think of yourself tossing coins with a biased outcome of 51 per cent -for heads and 49% for tails. With only few tosses, -you may not clearly see this distribution for heads and tails. However, after some -thousands of tosses, there will be a clear majority of heads. With 2000 tosses -you should see approximately 1020 heads and 980 tails. +
The idea behind boosting, and voting as well can be phrased as follows: +Can a group of people somehow arrive at highly +reasoned decisions, despite the weak judgement of the individual +members?
-We can then state that the outcome is a clear majority of heads. If -you do this ten thousand times, it is easy to see that there is a 97% -likelihood of a majority of heads. +
The aim is to create a good classifier by combining several weak classifiers. +A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.
-Another example would be to collect all polls before an -election. Different polls may show different likelihoods for a -candidate winning with say a majority of the popular vote. The majority vote -would then consist in many polls indicating that this candidate will -actually win. +
The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. +In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in +each iteration.
-The example here shows how we can implement the coin tossing case, -clealry demostrating that after some tosses we see the law of large -numbers kicking in. -
-======= - --We will grow of forest of say \( B \) trees. - -
Decision trees play an important role as our weak classifier. They serve as the basic method.
@@ -499,33 +430,22 @@ We will grow of forest of say \( B \) trees.
- -<<<<<<< HEAD -
The simplest case is a so-called voting ensemble. To illustrate this, +think of yourself tossing coins with a biased outcome of 51 per cent +for heads and 49% for tails. With only few tosses, +you may not clearly see this distribution for heads and tails. However, after some +thousands of tosses, there will be a clear majority of heads. With 2000 tosses +you should see approximately 1020 heads and 980 tails. +
- -# Common imports
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.tree import export_graphviz
-from sklearn.preprocessing import StandardScaler, OneHotEncoder
-from sklearn.compose import ColumnTransformer
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import os
+We can then state that the outcome is a clear majority of heads. If
+you do this ten thousand times, it is easy to see that there is a 97%
+likelihood of a majority of heads.
+
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
+Another example would be to collect all polls before an
+election. Different polls may show different likelihoods for a
+candidate winning with say a majority of the popular vote. The majority vote
+would then consist in many polls indicating that this candidate will
+actually win.
+
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
+The example here shows how we can implement the coin tossing case,
+clealry demostrating that after some tosses we see the law of large
+numbers kicking in.
+
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-- - -
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
-from sklearn.ensemble import BaggingClassifier
-
-# 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()
--Recall that the cumulative gains curve shows the percentage of the -overall number of cases in a given category gained by targeting a -percentage of the total number of cases. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-Similarly, the receiver operating characteristic curve, or ROC curve, -displays the diagnostic ability of a binary classifier system as its -discrimination threshold is varied. It plots the true positive rate against the false positive rate. - -
-
- -<<<<<<< HEAD -
# Common imports
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import pandas as pd
import numpy as np
-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.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import os
-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()
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
- - -
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)
-- - -
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)
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
+from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
+ # Common imports
+import numpy as np
+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
-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))
+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()
-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. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
from sklearn.metrics import accuracy_score
+
+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(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
+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
+
+from sklearn.metrics import accuracy_score
for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
@@ -541,59 +454,6 @@ voting_clf.fit(X_train, y_train)
-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 -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -
-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 - -$$ -\sigma(t) = \frac{1}{1+\exp{(-t)}}, -$$ - -
-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 -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -
-In this case the function \( f(x) \) was replaced by the design matrix -\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), -that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can -simply invert a matrix and obtain the parameters \( \beta \) by - -$$ -\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -
-In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). - -
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
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. -
+ +from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
-A fresh sample of \( m \) predictors is
-taken at each split, and typically we choose
-
+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
-$$
-m\approx \sqrt{p}.
-$$
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
-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.
-
+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
-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.
-
-=======
+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(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
-Iterative Fitting, Regression and Squared-error Cost Function
+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
-
-The way we proceed is as follows (here we specialize to the squared-error cost function)
+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))
+
+
-
- -<<<<<<< HEAD -
The algorithm described here can be applied to both classification and regression problems.
-======= +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. +
--To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +
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. +
-We will grow of forest of say \( B \) trees.
--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 +
A fresh sample of \( m \) predictors is +taken at each split, and typically we choose +
$$ -(\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. +m\approx \sqrt{p}. $$ --We start our iteration by simply setting \( f_0(x)=0 \). -Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -$$ -\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, -$$ +
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. +
-and -$$ -\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. -$$ +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. +
-We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) -$$ -\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, -$$ - -which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have -$$ -\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, -$$ - --which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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 \). - -
-
- -<<<<<<< HEAD -
The algorithm described here can be applied to both classification and regression problems.
- -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
-from sklearn.ensemble import BaggingClassifier
-
-# 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()
-
-Recall that the cumulative gains curve shows the percentage of the -overall number of cases in a given category gained by targeting a -percentage of the total number of cases. -
- -Similarly, the receiver operating characteristic curve, or ROC curve, -displays the diagnostic ability of a binary classifier system as its -discrimination threshold is varied. It plots the true positive rate against the false positive rate. -
-======= - --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 - -$$ -\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). -$$ - -
-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) \). ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-Here we will express our function \( f(x) \) in terms of \( G(x) \). That is -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -will be a function of -$$ -G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). -$$ - -
+
We will grow of forest of say \( B \) trees.
+-
- -<<<<<<< HEAD -
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)
-
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
+ 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
+from sklearn.ensemble import BaggingClassifier
+
+# 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
-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)
+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()
Recall that the cumulative gains curve shows the percentage of the +overall number of cases in a given category gained by targeting a +percentage of the total number of cases. +
-Similarly, the receiver operating characteristic curve, or ROC curve, +displays the diagnostic ability of a binary classifier system as its +discrimination threshold is varied. It plots the true positive rate against the false positive rate. +
--In our iterative procedure we define thus -$$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). -$$ - -
-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 -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. -$$ - -
-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 - -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, -$$ - -where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
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. -
+ +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)
+
+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)
+
+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. -
-======= ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e --First, for any \( \beta > 0 \), we optimize \( G \) by setting -$$ -G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), -$$ - -which is the classifier that minimizes the weighted error rate in predicting \( y \). - -
-We can do this by rewriting -$$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, -$$ - -which can be rewritten as -$$ -(\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, -$$ - -which leads to -$$ -\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, -$$ - -where we have redefined the error as -$$ -\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}, -$$ - -which leads to an update of -$$ -f_m(x) = f_{m-1}(x) +\beta_m G_m(x). -$$ - -This leads to the new weights -$$ -w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} -$$ - -
-
- -<<<<<<< HEAD -
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 -
-$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -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 \). +
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.
-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 +
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.
-$$ -\sigma(t) = \frac{1}{1+\exp{(-t)}}, -$$ - -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
-$$ -C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -In this case the function \( f(x) \) was replaced by the design matrix -\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), -that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can -simply invert a matrix and obtain the parameters \( \beta \) by -
- -$$ -\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).
-======= - --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 -\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{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 \( \boldsymbol{y} \). - -
-We have already defined the misclassification error \( \mathrm{err} \) as -$$ -\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), -$$ - -where the function \( I() \) is one if we misclassify and zero if we classify correctly. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
The way we proceed is as follows (here we specialize to the squared-error cost function)
+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 +
+$$ +f_M(x) = \sum_{i=1}^M \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. +
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 \).
-======= - --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. - -
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 +
$$ -\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}, +\sigma(t) = \frac{1}{1+\exp{(-t)}}, $$ +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
+$$ +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ -In this case the function \( f(x) \) was replaced by the design matrix +\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), +that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can +simply invert a matrix and obtain the parameters \( \beta \) by +
-In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -
-
- -<<<<<<< HEAD -
To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+The way we proceed is as follows (here we specialize to the squared-error cost 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
- -$$ -(\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. -$$ - -We start our iteration by simply setting \( f_0(x)=0 \). -Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -
-$$ -\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, -$$ - -and
-$$ -\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. -$$ - -We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
-$$ -\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, -$$ - -which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
-$$ -\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, -$$ - -which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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. +
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.
-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 \). -
-======= - --Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. - -
- - -
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
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-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()
-
-
- -<<<<<<< HEAD -
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\} \). +
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
+ +$$ +(\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. +$$ + +We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain +
+$$ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +$$ + +and
+$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ + +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
+$$ +\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, +$$ + +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
+$$ +\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, +$$ + +which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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 error rate of the training sample is then
- -$$ -\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). -$$ - -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) \). +
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 \).
-Here we will express our function \( f(x) \) in terms of \( G(x) \). That is
-$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -will be a function of
-$$ -G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). -$$ -======= - --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. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-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. - -
-
- -<<<<<<< HEAD -
In our iterative procedure we define thus
-$$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). -$$ - -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 -
-$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. -$$ - -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 +
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\} \).
-$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, -$$ - -where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
-======= - --We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize -This means that for every iteration, we need to optimize +
The error rate of the training sample is then
$$ -(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). $$ --We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +
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
$$ -f_M(x) = \sum_{m=0}^M h_m(x). +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ --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 +
will be a function of
$$ -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)}. -$$ ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - --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 -$$ -(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$ -
+
-
- -<<<<<<< HEAD -
First, for any \( \beta > 0 \), we optimize \( G \) by setting
+In our iterative procedure we define thus
$$ -G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). $$ -which is the classifier that minimizes the weighted error rate in predicting \( y \).
- -We can do this by rewriting
+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 +
$$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. $$ -which can be rewritten as
+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 +
+ $$ -(\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, +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, $$ -which leads to
-$$ -\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, -$$ +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
-where we have redefined the error as
-$$ -\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}, -$$ - -which leads to an update of
-$$ -f_m(x) = f_{m-1}(x) +\beta_m G_m(x). -$$ - -This leads to the new weights
-$$ -w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} -$$ - -======= - --Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that -$$ -f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. -$$ - -We can then proceed and compute -$$ -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, -$$ - -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. ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
-
- -<<<<<<< HEAD -
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 -\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{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 \( \boldsymbol{y} \). -
- -We have already defined the misclassification error \( \mathrm{err} \) as
+First, for any \( \beta > 0 \), we optimize \( G \) by setting
$$ -\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), $$ -where the function \( I() \) is one if we misclassify and zero if we classify correctly.
-======= +which is the classifier that minimizes the weighted error rate in predicting \( y \).
--Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, -so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. - -
-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 +
We can do this by rewriting
$$ -C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, $$ --The way we proceed in an iterative fashion is to +
which can be rewritten as
+$$ +(\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, +$$ -which leads to
+$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ -where we have redefined the error as
+$$ +\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}, +$$ + +which leads to an update of
+$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ + +This leads to the new weights
+$$ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +$$ -@@ -490,37 +446,27 @@ The way we proceed in an iterative fashion is to
- -<<<<<<< HEAD -
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. +
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 +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{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 \( \boldsymbol{y} \).
-We have already defined the misclassification error \( \mathrm{err} \) as
$$ -\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}, +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}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. -
-======= +where the function \( I() \) is one if we misclassify and zero if we classify correctly.
-- - -
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
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-# 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()
-
-
- -<<<<<<< HEAD -
Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
+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. +
+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. +
- -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()
-
-- - -
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)
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-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()
-
-
- -<<<<<<< HEAD -
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. -
+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-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. -
-======= -from sklearn.ensemble import AdaBoostClassifier
-
-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.
+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)
-
-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.
+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()
+
+-It is now the algorithm which wins essentially all ML competitions!!! ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -
-
- -<<<<<<< HEAD -
We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize -This means that for every iteration, we need to optimize +
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.
-$$ -(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
-$$ -f_M(x) = \sum_{m=0}^M h_m(x). -$$ - -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
-$$ -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)}. -$$ - -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)) \). +
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.
-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
-$$ -(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. -$$ - - -======= - -- - -
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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +This means that for every iteration, we need to optimize +
-Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
$$ -f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -We can then proceed and compute
+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
$$ -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, +f_M(x) = \sum_{m=0}^M h_m(x). $$ -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.
-======= +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
+$$ +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)}. +$$ -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)) \). +
--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. -
+
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
+$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ - -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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
@@ -513,37 +431,28 @@ plt.show()
- -<<<<<<< HEAD -
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, -so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -
- -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
+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
$$ -C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. $$ -The way we proceed in an iterative fashion is to
-We can then proceed and compute
+$$ +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, +$$ -+
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.
- -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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
- -<<<<<<< HEAD -
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
+Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
+so we do not learn a function that can generalize. However, we can modify the algorithm by
+fitting a weak learner to approximate the negative gradient signal.
+
-n = 100
-maxdegree = 6
+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
+$$
+C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+$$
-# 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()
-
--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. - -
-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!!! ->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e - -
+
The way we proceed in an iterative fashion is to
+-
- -<<<<<<< HEAD -
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +
import matplotlib.pyplot as plt
+
+
+
+
+
+ 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.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)
-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)))
+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]))
-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.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()
-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()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-
- -<<<<<<< HEAD -
-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. -
+
import matplotlib.pyplot as plt
+
+
+
+
+
+ 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
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
# Load the data
cancer = load_breast_cancer()
@@ -463,55 +415,41 @@ 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)
+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)))
-y_test = xg_clf.predict(X_test_scaled)
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-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.
-
-
-<<<<<<< HEAD
-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!!!
-=======
import scikitplot as skplt
-y_pred = xg_clf.predict(X_test_scaled)
+y_pred = gd_clf.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
-save_fig("xdclassiffierconfusion")
+save_fig("gdclassiffierconfusion")
plt.show()
-y_probas = xg_clf.predict_proba(X_test_scaled)
+y_probas = gd_clf.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
-save_fig("xdclassiffierroc")
+save_fig("gdclassiffierroc")
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()
-->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -
-
- - - -
-
- -
-
+
@@ -470,33 +429,22 @@ MathJax.Hub.Config({-
- -
-
-
-
-
- -Video on boosting methods by Hastie. +
-
+
-We start here with the most basic algorithm, the so-called decision +
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, +
Decision trees are supervised learning algorithms used for both, classification and regression tasks. +
--The main idea of decision trees +
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 +
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. +where we then finally end up in so called leaf nodes. +
-
+
-A decision tree is typically divided into a root node, the interior 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 +
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. +
-
+
-
+
-
+

-

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.
--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. - -
+
-The overarching approach to decision trees is a top-down approach. +
The overarching approach to decision trees is a top-down approach.
This process is then repeated for the subtree rooted at the new node. +
-
+
-In simplified terms, the process of training a decision tree and +
In simplified terms, the process of training a decision tree and predicting the target features of query instances is as follows: +
Then we are essentially done!
-Then we are essentially done! - -
-
-
+
import numpy as np
+
+
+
+
+
+ import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
@@ -477,7 +499,7 @@ c=lin_reg.intercept_
print ("first power: ", b[0])
print ("second power: ",b[1])
-z = np.arange(0, steps, .01)
+z = np.arange(0, steps, .01)
z_mod=b[1]*z**2+b[0]*z+c
fit_mod=b[1]*X**2+b[0]*X+c
@@ -527,96 +549,102 @@ plt.ylabel("Darget")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-There are mainly two steps - +
There are mainly two steps
How do we construct the regions \( R_1,\dots,R_J \)? In theory, the regions could have any shape. However, we choose to divide the predictor space into high-dimensional rectangles, or boxes, for simplicity and for ease of interpretation of the resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the MSE, given by +
$$ \sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, $$ --where \( \overline{y}_{R_j} \) is the mean response for the training observations -within box \( j \). +
where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). +
-
+
-Unfortunately, it is computationally infeasible to consider every +
Unfortunately, it is computationally infeasible to consider every possible partition of the feature space into \( J \) boxes. The common strategy is to take a top-down approach +
--The approach is top-down because it begins at the top of the tree (all +
The approach is top-down because it begins at the top of the tree (all observations belong to a single region) and then successively splits the predictor space; each split is indicated via two new branches further down on the tree. It is greedy because at each step of the tree-building process, the best split is made at that particular step, rather than looking ahead and picking a split that will lead to a better tree in some future step. +
-
+
-In order to implement the recursive binary splitting we start by selecting +
In order to implement the recursive binary splitting we start by selecting the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +
$$ \left\{X\vert x_j < s\right\}, $$ -and +and
$$ \left\{X\vert x_j \geq s\right\}, $$ -so that we obtain the lowest MSE, that is +so that we obtain the lowest MSE, that is
$$ \sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, $$ --which we want to minimize by considering all predictors +
which we want to minimize by considering all predictors \( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value. +
--For any \( j \) and \( s \), we define the pair of half-planes where +
For any \( j \) and \( s \), we define the pair of half-planes where \( \overline{y}_{R_1} \) is the mean response for the training observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean response for the training observations in \( R_2(j,s) \). +
--Finding the values of \( j \) and \( s \) that minimize the above equation can be +
Finding the values of \( j \) and \( s \) that minimize the above equation can be done quite quickly, especially when the number of features \( p \) is not too large. +
--Next, we repeat the process, looking +
Next, we repeat the process, looking for the best predictor and best cutpoint in order to split the data further so as to minimize the MSE within each of the resulting regions. However, this time, instead of splitting the entire predictor @@ -625,95 +653,83 @@ have three regions. Again, we look to split one of these three regions further, so as to minimize the MSE. The process continues until a stopping criterion is reached; for instance, we may continue until no region contains more than five observations. +
-+
-The above procedure is rather straightforward, but leads often to +
The above procedure is rather straightforward, but leads often to overfitting and unnecessarily large and complicated trees. The basic idea is to grow a large tree \( T_0 \) and then prune it back in order to obtain a subtree. A smaller tree with fewer splits (fewer regions) can lead to smaller variance and better interpretation at the cost of a little more bias. +
--The so-called Cost complexity pruning algorithm gives us a +
The so-called Cost complexity pruning algorithm gives us a way to do just this. Rather than considering every possible subtree, we consider a sequence of trees indexed by a nonnegative tuning parameter \( \alpha \). +
--Read more at the following Scikit-Learn link on pruning. +
Read more at the following Scikit-Learn link on pruning.
-
+
-For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +
For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
$$ \sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, $$ -is as small as possible. Here \( \overline{T} \) is +is as small as possible. Here \( \overline{T} \) is the number of terminal nodes of the tree \( T \) , \( R_m \) is the rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. +
--The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +
The tuning parameter \( \alpha \) controls a trade-off between the subtree’s complexity and its fit to the training data. When \( \alpha = 0 \), then the subtree \( T \) will simply equal \( T_0 \), because then the above equation just measures the training error. However, as \( \alpha \) increases, there is a price to pay for having a tree with many terminal nodes. The above equation will -tend to be minimized for a smaller subtree. +tend to be minimized for a smaller subtree. +
--It turns out that as we increase \( \alpha \) from zero +
It turns out that as we increase \( \alpha \) from zero branches get pruned from the tree in a nested and predictable fashion, so obtaining the whole sequence of subtrees as a function of \( \alpha \) is easy. We can select a value of \( \alpha \) using a validation set or using cross-validation. We then return to the full data set and obtain the -subtree corresponding to \( \alpha \). +subtree corresponding to \( \alpha \). +
-
+
+
-A classification tree is very similar to a regression tree, except +
A classification tree is very similar to a regression tree, except that it is used to predict a qualitative response rather than a quantitative one. Recall that for a regression tree, the predicted response for an observation is given by the mean response of the @@ -724,15 +740,13 @@ in the region to which it belongs. In interpreting the results of a classification tree, we are often interested not only in the class prediction corresponding to a particular terminal node region, but also in the class proportions among the training observations that -fall into that region. +fall into that region. +
-
+
-The task of growing a +
The task of growing a classification tree is quite similar to the task of growing a regression tree. Just as in the regression setting, we use recursive binary splitting to grow a classification tree. However, in the @@ -742,68 +756,61 @@ error rate. Since we plan to assign an observation in a given region to the most commonly occurring error rate class of training observations in that region, the classification error rate is simply the fraction of the training observations in that region that do not -belong to the most common class. +belong to the most common class. +
--When building a classification tree, either the Gini index or the +
When building a classification tree, either the Gini index or the entropy are typically used to evaluate the quality of a particular split, since these two approaches are more sensitive to node purity -than is the classification error rate. +than is the classification error rate. +
-
+
-If our targets are the outcome of a classification process that takes +
If our targets are the outcome of a classification process that takes for example \( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node. +
--We define a PDF \( p_{mk} \) that represents the number of observations of +
We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as +
$$ p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). $$ --We let \( p_{mk} \) represent the majority class of observations in region +
We let \( p_{mk} \) represent the majority class of observations in region \( m \). The three most common ways of splitting a node are given by +
+
-<<<<<<< HEAD
-
The Gini index \( g \) gives us the degree of probability of a specific variable that is wrongly classified. @@ -818,7 +825,7 @@ variable that is wrongly classified.
It favors binary splitting.
It is custom to split to a tree uising binary splits. The reason is that multiway splits fragment the data too quickly, leaving @@ -827,15 +834,81 @@ achieved by a series of binary split and this is normally preferred.
Consider the following example with attributes/features and two +possible outcomes (classes) for each attribute. Assume we wish to find some +correlations between the average grade of a student as function of the +number of hours studied and hours slept. We want also to correlate the +grade in a given course with the general trend, whether the students +recently has gotten grades below average or above. +
+ +We have three features/attributes
+| Grade Trend | Hours slept | Hours Studied | Grade |
|---|
In computations we will translate all classes into numbers. Being +these binary classes, they can easily be split into ones and zeros. +
+ +->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + + +
+ + +
+ + +
import os
+
+
+
+
+
+ import os
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
@@ -868,15 +941,32 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
os.system(cmd)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
@@ -900,39 +990,72 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
os.system(cmd)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.
--Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. - -
-
from sklearn.datasets import load_iris
+
+
+
+
+
+ from sklearn.datasets import load_iris
from sklearn import tree
X, y = load_iris(return_X_y=True)
tree_clf = tree.DecisionTreeClassifier()
tree_clf = tree_clf.fit(X, y)
# and then plot the tree
tree.plot_tree(tree_clf)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-Alternatively, the tree can also be exported in textual format with the function exporttext. +
Alternatively, the tree can also be exported in textual format with the function exporttext. This method doesn’t require the installation of external libraries and is more compact: +
--
from sklearn.datasets import load_iris
+
+
+
+
+
+ from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
@@ -940,87 +1063,92 @@ decision_tree = DecisionTreeClassifier(random_state='feature_names'])
print(r)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-Two algorithms stand out in the set up of decision trees: - +
Two algorithms stand out in the set up of decision trees:
We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. +
-
+
-For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +
For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). This could be for example a threshold set by a number below a certain circumference of a malign tumor. +
--How do we find these two quantities? +
How do we find these two quantities? We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). The cost function it tries to minimize is then +
$$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, $$ -where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) is the number of instances in the left/right subset +
--Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +
Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the \( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), \( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). +
-
+
-The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +
The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +
$$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. $$ -Here the MSE for a specific node is defined as +Here the MSE for a specific node is defined as
$$ \mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, $$ -with +with
$$ \overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, $$ -the mean value of all observations in a specific node. +the mean value of all observations in a specific node.
--Without any regularization, the regression task for decision trees, +
Without any regularization, the regression task for decision trees, just like for classification tasks, is prone to overfitting. +
-
+
-The example we will look at is a classical one in many Machine +
The example we will look at is a classical one in many Machine Learning applications. Based on various meteorological features, we have several so-called attributes which decide whether we at the end will do some outdoor activity like skiing, going for a bike ride etc @@ -1030,10 +1158,10 @@ etc. The table here contains the feautures outlook, temperature, attributes for each feature are then sunny, overcast and rain for the outlook, hot, cold and mild for temperature, high and normal for humidity and weak and strong for wind. +
--The table here summarizes the various attributes and -
| Day | Outlook | Temperature | Humidity | Wind | Ride |
|---|---|---|---|---|---|
| 14 | Rain | Mild | High | Strong | 0 |
+
+
-
# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -1129,25 +1260,41 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
os.system(cmd)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-The above functions (gini, entropy and misclassification error) are +
The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm below after we have discussed the information gain algorithm ID3. +
--In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. +
In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.
--
# Split a dataset based on an attribute and an attribute value
+
+
+
+
+
+ # Split a dataset based on an attribute and an attribute value
def test_split(index, value, dataset):
left, right = list(), list()
for row in dataset:
@@ -1207,15 +1354,28 @@ dataset = [[0,0
split = get_split(dataset)
print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+-The ID3 algorithm learns decision trees by constructing +
The ID3 algorithm learns decision trees by constructing them in a top down way, beginning with the question which attribute should be tested at the root of the tree? +
The ID3 algorithm selects which attribute to test at each node in the tree. +
--We would like to select the attribute that is most useful for classifying +
We would like to select the attribute that is most useful for classifying examples. +
--What is a good quantitative measure of the worth of an attribute? +
What is a good quantitative measure of the worth of an attribute?
--Information gain measures how well a given attribute separates the +
Information gain measures how well a given attribute separates the training examples according to their target classification. +
--The ID3 algorithm uses this information gain measure to select among the candidate +
The ID3 algorithm uses this information gain measure to select among the candidate attributes at each step while growing the tree. +
-
-
-
+
import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -1292,15 +1453,32 @@ svm.fit(X_train_scaled, y_train)
# 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 __future__ import division, print_function, unicode_literals
+
+
+
+
+
+ from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
@@ -1364,15 +1542,32 @@ 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()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
np.random.seed(6)
+
+
+
+
+
+ np.random.seed(6)
Xs = np.random.rand(100, 2) - 0.5
ys = (Xs[:, 0] > 0).astype(np.float32) * 2
@@ -1392,37 +1587,86 @@ plt.subplot(122)
plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# Quadratic training set + noise
+
+
+
+
+
+ # 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
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-from sklearn.tree import DecisionTreeRegressor
+
+
+
+
+
+ from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
tree_reg.fit(X, y)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Final regressor code
-
+
+
+
Final regressor code
-from sklearn.tree import DecisionTreeRegressor
+
+
+
+
+
+ from sklearn.tree import DecisionTreeRegressor
tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
@@ -1460,11 +1704,26 @@ plt.text(0.3, 0
plt.title("max_depth=3", fontsize=14)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-tree_reg1 = DecisionTreeRegressor(random_state=42)
+
+
+
+
+
+ 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)
@@ -1492,11 +1751,24 @@ plt.xlabel("$x_1$", fontsize="min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Pros and cons of trees, pros
+
+
+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)
@@ -1507,10 +1779,8 @@ plt.show()
- 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
+Disadvantages
- Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
@@ -1521,28 +1791,26 @@ plt.show()
- 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
+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
-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
+
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
+
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
+
- Voting classifiers
@@ -1550,50 +1818,45 @@ try to explain here. These are
- Random forests
- Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+We discuss these methods here.
-We discuss these methods here.
-
-
+
An Overview of Ensemble Methods
-An Overview of Ensemble Methods
+
+
+
+
+
-
-

-
-
+
Bagging
-Bagging
-
-
-The plain decision trees suffer from high
+
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.
+of \( n \) to \( p \) is moderately large.
+
-
-Bootstrap aggregation, or just bagging, is a
+
Bootstrap aggregation, or just bagging, is a
general-purpose procedure for reducing the variance of a statistical
-learning method.
+learning method.
+
-
+
More bagging
-More bagging
-
-
-Bagging typically results in improved accuracy
+
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
+
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
@@ -1608,19 +1871,22 @@ 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.
+
-
+
Making your own Bootstrap: Changing the Level of the Decision Tree
-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
+
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 \)).
-
+
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
@@ -1671,69 +1937,81 @@ plt.plot(polydegree, variance, label='Variance&
plt.legend()
save_fig("baggingboot")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Why Voting?
-Why Voting?
-
-
-The idea behind boosting, and voting as well can be phrased as follows:
+
The idea behind boosting, and voting as well can be phrased as follows:
Can a group of people somehow arrive at highly
reasoned decisions, despite the weak judgement of the individual
members?
+
-
-The aim is to create a good classifier by combining several weak classifiers.
+
The aim is to create a good classifier by combining several weak classifiers.
A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.
+
-
-The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
+
The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in
-each iteration.
+each iteration.
+
-
-Decision trees play an important role as our weak classifier. They serve as the basic method.
+
Decision trees play an important role as our weak classifier. They serve as the basic method.
-
+
Tossing coins
-Tossing coins
-
-
-The simplest case is a so-called voting ensemble. To illustrate this,
+
The simplest case is a so-called voting ensemble. To illustrate this,
think of yourself tossing coins with a biased outcome of 51 per cent
for heads and 49% for tails. With only few tosses,
you may not clearly see this distribution for heads and tails. However, after some
thousands of tosses, there will be a clear majority of heads. With 2000 tosses
you should see approximately 1020 heads and 980 tails.
+
-
-We can then state that the outcome is a clear majority of heads. If
+
We can then state that the outcome is a clear majority of heads. If
you do this ten thousand times, it is easy to see that there is a 97%
likelihood of a majority of heads.
+
-
-Another example would be to collect all polls before an
+
Another example would be to collect all polls before an
election. Different polls may show different likelihoods for a
candidate winning with say a majority of the popular vote. The majority vote
would then consist in many polls indicating that this candidate will
actually win.
+
-
-The example here shows how we can implement the coin tossing case,
+
The example here shows how we can implement the coin tossing case,
clealry demostrating that after some tosses we see the law of large
numbers kicking in.
+
-
+
Standard imports first
-Standard imports first
-
-
-
# Common imports
+
+
+
+
+
+ # Common imports
from IPython.display import Image
from pydot import graph_from_dot_data
import pandas as pd
@@ -1770,15 +2048,32 @@ DATA_ID = "DataFiles/"
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Simple Voting Example, head or tail
-
+
+
+
Simple Voting Example, head or tail
-# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
@@ -1800,18 +2095,34 @@ plt.legend(loc="lower right")
plt.axis([0, 10000, 0.42, 0.58])
save_fig("votingsimple")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Using the Voting Classifier
-Using the Voting Classifier
-
-
-We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
-
+
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
-from sklearn.model_selection import train_test_split
+
+
+
+
+
+ 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)
@@ -1853,16 +2164,33 @@ voting_clf.fit(X_train, y_train)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Voting and Bagging
-Voting and Bagging
-
-
-
from sklearn.model_selection import train_test_split
+
+
+
+
+
+ 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)
@@ -1880,21 +2208,51 @@ 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
+
+
+
+
+
+ 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(random_state=42)
+
+
+
+
+
+ log_clf = LogisticRegression(random_state=42)
rnd_clf = RandomForestClassifier(random_state=42)
svm_clf = SVC(probability=True, random_state=42)
@@ -1902,49 +2260,76 @@ 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
+
+
+
+
+
+ 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))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Random forests
-Random forests
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
-
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
-
-
-As in bagging, we build a
+
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.
+use only one of those \( m \) predictors.
+
-
-A fresh sample of \( m \) predictors is
+
A fresh sample of \( m \) predictors is
taken at each split, and typically we choose
+
$$
m\approx \sqrt{p}.
$$
-
-In building a random forest, at
+
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.
+a majority of the available predictors.
+
-
-The reason for this is rather clever. Suppose that there is one very
+
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
@@ -1956,41 +2341,36 @@ 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.
-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.
-
+
We will grow of forest of say \( B \) trees.
- For \( b=1:B \)
-
- Draw a bootstrap sample from the training data organized in our \( \boldsymbol{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
-
- we select \( m \le p \) variables at random from the \( p \) predictors/features
- pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
- split the node into daughter nodes
-
-
- 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
-
+
Random Forests Compared with other Methods on the Cancer Data
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2056,362 +2436,374 @@ skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
-
-
-Recall that the cumulative gains curve shows the percentage of the
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Recall that the cumulative gains curve shows the percentage of the
overall number of cases in a given category gained by targeting a
percentage of the total number of cases.
+
-
-Similarly, the receiver operating characteristic curve, or ROC curve,
+
Similarly, the receiver operating characteristic curve, or ROC curve,
displays the diagnostic ability of a binary classifier system as its
discrimination threshold is varied. It plots the true positive rate against the false positive rate.
+
-
-
-
Compare Bagging on Trees with Random Forests
-
+
Compare Bagging on Trees with Random Forests
-bag_clf = BaggingClassifier(
+
+
+
+
+
+ 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)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-bag_clf.fit(X_train, y_train)
+
+
+
+
+
+ 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)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Boosting, a Bird's Eye View
-Boosting, a Bird's Eye View
-
-
-The basic idea is to combine weak classifiers in order to create a good
+
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
+
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
-What is boosting? Additive Modelling/Iterative Fitting
-
-
-Boosting is a way of fitting an additive expansion in a set of
+
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
+
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
-
-where \( \beta_m \) are the expansion parameters to be determined in a
+
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
+
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
+
$$
\sigma(t) = \frac{1}{1+\exp{(-t)}},
$$
-
-where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and
+
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
+
As another example, consider the cost function we defined for linear regression
$$
C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-In this case the function \( f(x) \) was replaced by the design matrix
+
In this case the function \( f(x) \) was replaced by the design matrix
\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \),
that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can
simply invert a matrix and obtain the parameters \( \beta \) by
+
$$
\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
-
-In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).
+
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
-Iterative Fitting, Regression and Squared-error Cost Function
-
-
-The way we proceed is as follows (here we specialize to the squared-error cost function)
+
The way we proceed is as follows (here we specialize to the squared-error cost function)
- Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
- Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
- For \( m=1:M \)
-
- minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
- This gives the optimal values \( \beta_m \) and \( \gamma_m \)
- 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
+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
-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.
-
-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 \).
-
-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
+
This means that for every iteration \( m \), we need to optimize
$$
(\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.
$$
-
-We start our iteration by simply setting \( f_0(x)=0 \).
+
We start our iteration by simply setting \( f_0(x)=0 \).
Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
+
$$
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
$$
-and
+and
$$
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
$$
-We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
+We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
$$
\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
$$
-which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
+which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
$$
\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
$$
-
-which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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.
+
which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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 \).
+
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
-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
+
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
+
The error rate of the training sample is then
$$
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
$$
-
-The iterative procedure starts with defining a weak classifier whose
+
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
+
Here we will express our function \( f(x) \) in terms of \( G(x) \). That is
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
-will be a function of
+will be a function of
$$
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
$$
-
+
+
Adaptive Boosting, AdaBoost
-Adaptive Boosting, AdaBoost
-
-
-In our iterative procedure we define thus
+
In our iterative procedure we define thus
$$
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
$$
-
-The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
+
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
+
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
$$
-
-We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case.
+
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
+
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
$$
-where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
+where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
-
+
Building up AdaBoost
-Building up AdaBoost
-
-
-First, for any \( \beta > 0 \), we optimize \( G \) by setting
+
First, for any \( \beta > 0 \), we optimize \( G \) by setting
$$
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
$$
-which is the classifier that minimizes the weighted error rate in predicting \( y \).
+which is the classifier that minimizes the weighted error rate in predicting \( y \).
-
-We can do this by rewriting
+
We can do this by rewriting
$$
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
$$
-which can be rewritten as
+which can be rewritten as
$$
(\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,
$$
-which leads to
+which leads to
$$
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
$$
-where we have redefined the error as
+where we have redefined the error as
$$
\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},
$$
-which leads to an update of
+which leads to an update of
$$
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
$$
-This leads to the new weights
+This leads to the new weights
$$
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
$$
-
+
+
Adaptive boosting: AdaBoost, Basic Algorithm
-Adaptive boosting: AdaBoost, Basic Algorithm
-
-
-The algorithm here is rather straightforward. Assume that our weak
+
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
\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{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 \( \boldsymbol{y} \).
+classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \).
+
-
-We have already defined the misclassification error \( \mathrm{err} \) as
+
We have already defined the misclassification error \( \mathrm{err} \) as
$$
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
$$
-where the function \( I() \) is one if we misclassify and zero if we classify correctly.
+where the function \( I() \) is one if we misclassify and zero if we classify correctly.
-
+
Basic Steps of AdaBoost
-Basic Steps of AdaBoost
-
-
-With the above definitions we are now ready to set up the algorithm for 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.
-
+
- 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 \).
- We rewrite the misclassification error as
-
$$
\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},
$$
-
- 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.
-
- Fit then a given classifier to the training set using the weights \( w_i \).
- Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
- Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
- Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
-
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
+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
-AdaBoost Examples
+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-
-Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-
-
-
from sklearn.ensemble import AdaBoostClassifier
+
+
+
+
+
+ from sklearn.ensemble import AdaBoostClassifier
ada_clf = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1), n_estimators=200,
@@ -2432,114 +2824,115 @@ skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-
-
-Gradient boosting is again a similar technique to Adaptive boosting,
+
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
+
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
-The Squared-Error again! Steepest Descent
-
-
-We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
+
We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
This means that for every iteration, we need to optimize
+
$$
(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
+
We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
$$
f_M(x) = \sum_{m=0}^M h_m(x).
$$
-
-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
+
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
$$
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)}.
$$
-
-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
+
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
+
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
$$
(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
$$
-
+
+
Steepest Descent Example
-Steepest Descent Example
-
-
-Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
+
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
$$
f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
$$
-We can then proceed and compute
+We can then proceed and compute
$$
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,
$$
-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.
+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
-Gradient Boosting, algorithm
-
-
-Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
+
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
so we do not learn a function that can generalize. However, we can modify the algorithm by
-fitting a weak learner to approximate the negative gradient signal.
+fitting a weak learner to approximate the negative gradient signal.
+
-
-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
+
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
$$
C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-The way we proceed in an iterative fashion is to
-
+
The way we proceed in an iterative fashion is to
- Initialize our estimate \( f_0(x) \).
- For \( m=1:M \), we
-
- compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
- fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
- update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
-
The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
-
-
-Gradient Boosting, Examples of Regression
-
+
Gradient Boosting, Examples of Regression
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
@@ -2585,15 +2978,32 @@ plt.plot(polydegree, variance, label='Variance&
plt.legend()
save_fig("gdregression")
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Gradient Boosting, Classification Example
-
+
+
+
Gradient Boosting, Classification Example
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2633,37 +3043,51 @@ plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
save_fig("gdclassiffiercgain")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+XGBoost: Extreme Gradient Boosting
-XGBoost: Extreme Gradient Boosting
-
-
-XGBoost or Extreme Gradient
+
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.
+
-
-The authors design and build a highly scalable end-to-end tree
+
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!!!
+
It is now the algorithm which wins essentially all ML competitions!!!
-
+
Regression Case
-Regression Case
-
-
-
import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import xgboost as xgb
@@ -2709,18 +3133,34 @@ plt.plot(polydegree, bias, label='bias''Variance')
plt.legend()
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Xgboost on the Cancer Data
-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.
-
+
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.
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2771,18 +3211,26 @@ xgb.plot_importance(xg_clf)
plt.rcParams['figure.figsize'] = [5, 5]
save_fig("xgparams")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
© 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
-
-
-
diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html
index c1df18d71..9f66f6a0d 100644
--- a/doc/pub/week45/html/week45.html
+++ b/doc/pub/week45/html/week45.html
@@ -1,36 +1,105 @@
-
+
-
Week 45: Decisions Trees, Random Forests, Bagging and Boosting
-
-
-
-
@@ -264,150 +387,122 @@ MathJax.Hub.Config({
-
-
+
+Week 45: Decisions Trees, Random Forests, Bagging and Boosting
+
-
-
-Week 45: Decisions Trees, Random Forests, Bagging and Boosting
-
-
-
Morten Hjorth-Jensen [1, 2]
-
-
-
-
[1] Department of Physics, University of Oslo
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+[1] Department of Physics, University of Oslo
+
+
+[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
-<<<<<<< HEAD
Nov 11, 2021
-=======
-
-
Nov 10, 2021
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
-
-
-
Overview of week 45
+
+Overview of week 45
- Thursday: Basics of Decision Trees, Bagging and Voting
- Friday: More on Bagging, Voting, Random Forests and start Boosting
-
-Videos.
+Videos
-
-
-Video on boosting methods by Hastie.
+
-
-Reading.
+Reading
-
- Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.
-
+
Decision trees, overarching aims
-Decision trees, overarching aims
-
-
-We start here with the most basic algorithm, the so-called decision
+
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,
+
Decision trees are supervised learning algorithms used for both,
classification and regression tasks.
+
-
-The main idea of decision trees
+
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
+
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.
+where we then finally end up in so called leaf nodes.
+
-
+
Basics of a tree
-Basics of a tree
-
-
-A decision tree is typically divided into a root node, the interior 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
+
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 Sketch of a Tree, Regression problem
-A Sketch of a Tree, Regression problem
-
-
-
+
A Sketch of a Tree, Classification problem
-A Sketch of a Tree, Classification problem
-
-
-
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
-A typical Decision Tree with its pertinent Jargon, Classification Problem
+
+
+
+
+
-
-

+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.
-
-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
-General Features
-
-
-The overarching approach to decision trees is a top-down approach.
+
The overarching approach to decision trees is a top-down approach.
- A leaf provides the classification of a given instance.
@@ -415,18 +510,16 @@ The overarching approach to decision trees is a top-down approach.
- 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
+This process is then repeated for the subtree rooted at the new
node.
+
-
+
How do we set it up?
-How do we set it up?
-
-
-In simplified terms, the process of training a decision tree and
+
In simplified terms, the process of training a decision tree and
predicting the target features of query instances is as follows:
+
- Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
@@ -434,17 +527,18 @@ predicting the target features of query instances is as follows:
- Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
- Show query instances to the tree and run down the tree until we arrive at leaf nodes
+Then we are essentially done!
-Then we are essentially done!
-
-
-
-
Decision trees and Regression
-
+
Decision trees and Regression
-import numpy as np
+
+
+
+
+
+ import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
@@ -532,96 +626,102 @@ plt.ylabel(&quo
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Building a tree, regression
-Building a tree, regression
-
-
-There are mainly two steps
-
+
There are mainly two steps
- We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
- For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
-
-How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
regions could have any shape. However, we choose to divide the
predictor space into high-dimensional rectangles, or boxes, for
simplicity and for ease of interpretation of the resulting predictive
model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
MSE, given by
+
$$
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
$$
-
-where \( \overline{y}_{R_j} \) is the mean response for the training observations
-within box \( j \).
+
where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+
-
+
A top-down approach, recursive binary splitting
-A top-down approach, recursive binary splitting
-
-
-Unfortunately, it is computationally infeasible to consider every
+
Unfortunately, it is computationally infeasible to consider every
possible partition of the feature space into \( J \) boxes. The common
strategy is to take a top-down approach
+
-
-The approach is top-down because it begins at the top of the tree (all
+
The approach is top-down because it begins at the top of the tree (all
observations belong to a single region) and then successively splits
the predictor space; each split is indicated via two new branches
further down on the tree. It is greedy because at each step of the
tree-building process, the best split is made at that particular step,
rather than looking ahead and picking a split that will lead to a
better tree in some future step.
+
-
+
Making a tree
-Making a tree
-
-
-In order to implement the recursive binary splitting we start by selecting
+
In order to implement the recursive binary splitting we start by selecting
the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+
$$
\left\{X\vert x_j < s\right\},
$$
-and
+and
$$
\left\{X\vert x_j \geq s\right\},
$$
-so that we obtain the lowest MSE, that is
+so that we obtain the lowest MSE, that is
$$
\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
$$
-
-which we want to minimize by considering all predictors
+
which we want to minimize by considering all predictors
\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
each predictor. These values could be determined by randomly assigned
numbers or by starting at the midpoint and then proceed till we find
an optimal value.
+
-
-For any \( j \) and \( s \), we define the pair of half-planes where
+
For any \( j \) and \( s \), we define the pair of half-planes where
\( \overline{y}_{R_1} \) is the mean response for the training
observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
response for the training observations in \( R_2(j,s) \).
+
-
-Finding the values of \( j \) and \( s \) that minimize the above equation can be
+
Finding the values of \( j \) and \( s \) that minimize the above equation can be
done quite quickly, especially when the number of features \( p \) is not
too large.
+
-
-Next, we repeat the process, looking
+
Next, we repeat the process, looking
for the best predictor and best cutpoint in order to split the data
further so as to minimize the MSE within each of the resulting
regions. However, this time, instead of splitting the entire predictor
@@ -630,95 +730,83 @@ have three regions. Again, we look to split one of these three regions
further, so as to minimize the MSE. The process continues until a
stopping criterion is reached; for instance, we may continue until no
region contains more than five observations.
+
-
+
Pruning the tree
-Pruning the tree
-
-
-The above procedure is rather straightforward, but leads often to
+
The above procedure is rather straightforward, but leads often to
overfitting and unnecessarily large and complicated trees. The basic
idea is to grow a large tree \( T_0 \) and then prune it back in order to
obtain a subtree. A smaller tree with fewer splits (fewer regions) can
lead to smaller variance and better interpretation at the cost of a
little more bias.
+
-
-The so-called Cost complexity pruning algorithm gives us a
+
The so-called Cost complexity pruning algorithm gives us a
way to do just this. Rather than considering every possible subtree,
we consider a sequence of trees indexed by a nonnegative tuning
parameter \( \alpha \).
+
-
-Read more at the following Scikit-Learn link on pruning.
+
Read more at the following Scikit-Learn link on pruning.
-
+
Cost complexity pruning
-Cost complexity pruning
-
-
-For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
+
For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
$$
\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
$$
-is as small as possible. Here \( \overline{T} \) is
+is as small as possible. Here \( \overline{T} \) is
the number of terminal nodes of the tree \( T \) , \( R_m \) is the
rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
+
-
-The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
+
The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
complexity and its fit to the training data. When \( \alpha = 0 \), then the
subtree \( T \) will simply equal \( T_0 \),
because then the above equation just measures the
training error.
However, as \( \alpha \) increases, there is a price to pay for
having a tree with many terminal nodes. The above equation will
-tend to be minimized for a smaller subtree.
+tend to be minimized for a smaller subtree.
+
-
-It turns out that as we increase \( \alpha \) from zero
+
It turns out that as we increase \( \alpha \) from zero
branches get pruned from the tree in a nested and predictable fashion,
so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
easy. We can select a value of \( \alpha \) using a validation set or using
cross-validation. We then return to the full data set and obtain the
-subtree corresponding to \( \alpha \).
+subtree corresponding to \( \alpha \).
+
-
+
Schematic Regression Procedure
-Schematic Regression Procedure
-
-
-Building a Regression Tree.
+Building a Regression Tree
- Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
- Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
- Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
-
- repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
- Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
- Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
-
- Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
-
+
A Classification Tree
-A Classification Tree
-
-
-A classification tree is very similar to a regression tree, except
+
A classification tree is very similar to a regression tree, except
that it is used to predict a qualitative response rather than a
quantitative one. Recall that for a regression tree, the predicted
response for an observation is given by the mean response of the
@@ -729,15 +817,13 @@ in the region to which it belongs. In interpreting the results of a
classification tree, we are often interested not only in the class
prediction corresponding to a particular terminal node region, but
also in the class proportions among the training observations that
-fall into that region.
+fall into that region.
+
-
+
Growing a classification tree
-Growing a classification tree
-
-
-The task of growing a
+
The task of growing a
classification tree is quite similar to the task of growing a
regression tree. Just as in the regression setting, we use recursive
binary splitting to grow a classification tree. However, in the
@@ -747,68 +833,61 @@ error rate. Since we plan to assign an observation in a given region
to the most commonly occurring error rate class of training
observations in that region, the classification error rate is simply
the fraction of the training observations in that region that do not
-belong to the most common class.
+belong to the most common class.
+
-
-When building a classification tree, either the Gini index or the
+
When building a classification tree, either the Gini index or the
entropy are typically used to evaluate the quality of a particular
split, since these two approaches are more sensitive to node purity
-than is the classification error rate.
+than is the classification error rate.
+
-
+
Classification tree, how to split nodes
-Classification tree, how to split nodes
-
-
-If our targets are the outcome of a classification process that takes
+
If our targets are the outcome of a classification process that takes
for example \( k=1,2,\dots,K \) values, the only thing we need to think of
is to set up the splitting criteria for each node.
+
-
-We define a PDF \( p_{mk} \) that represents the number of observations of
+
We define a PDF \( p_{mk} \) that represents the number of observations of
a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
this likelihood function in terms of the proportion \( I(y_i=k) \) of
observations of this class in the region \( R_m \) as
+
$$
p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k).
$$
-
-We let \( p_{mk} \) represent the majority class of observations in region
+
We let \( p_{mk} \) represent the majority class of observations in region
\( m \). The three most common ways of splitting a node are given by
+
- Misclassification error
-
$$
\frac{1}{N_m}\sum_{i\in R_m}I(y_i\ne k) = 1-p_{mk}.
$$
-
- Gini index \( g \)
-
$$
g = \sum_{k\ne k'} p_{mk}p_{mk'}=\sum_{k=1}^K p_{mk}(1-p_{mk}).
$$
-
- Information entropy or just entropy \( s \)
-
$$
s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
$$
-
+
-<<<<<<< HEAD
-
Gini Index?Coefficient/Impurity
+Gini Index (or Coefficient or Impurity)
The Gini index \( g \) gives us the degree of probability of a specific
variable that is wrongly classified.
@@ -823,7 +902,7 @@ variable that is wrongly classified.
It favors binary splitting.
-Why binary split?
+Why binary splits?
It is custom to split to a tree uising binary splits. The reason is
that multiway splits fragment the data too quickly, leaving
@@ -832,15 +911,81 @@ achieved by a series of binary split and this is normally preferred.
-Visualizing the Tree, Classification
-=======
+Computing a Tree using the Gini Index
-Visualizing the Tree, Classification
+Consider the following example with attributes/features and two
+possible outcomes (classes) for each attribute. Assume we wish to find some
+correlations between the average grade of a student as function of the
+number of hours studied and hours slept. We want also to correlate the
+grade in a given course with the general trend, whether the students
+recently has gotten grades below average or above.
+
+
+We have three features/attributes
+
+- Trend of average grades before present course, classified as either below or above the average grade of the whole class
+- The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one \( ECTS \) which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.
+- The number of hours slept as high for more than \( 8 \) hours and below for less than 8 hours of sleep, classified again as either high or low
+- The final grade whether it is above or below average
+
+
+The Table
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+
+
+
+
+
+
+Computing the various Gini Indices
+
+In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+
+
+
+Gini index for Average trend
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+
+
+
+
+
+
+Computing the various Gini Indices, Hours slept
+
+
+Gini index for hour slept
+
+
+
+
+
+
+
+Computing the various Gini Indices, Hours studied
+
+
+Gini index for hour studied
+
+
+
+
+
+
+
+Visualizing the Tree, Classification
-import os
+
+
+
+
+
+ import os
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
@@ -873,15 +1018,32 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
os.system(cmd)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Visualizing the Tree, The Moons
-
+
+
+
Visualizing the Tree, The Moons
-# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
@@ -905,39 +1067,72 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
os.system(cmd)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Other ways of visualizing the trees
-Other ways of visualizing the trees
+Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.
-
-Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.
-
-
-
from sklearn.datasets import load_iris
+
+
+
+
+
+ from sklearn.datasets import load_iris
from sklearn import tree
X, y = load_iris(return_X_y=True)
tree_clf = tree.DecisionTreeClassifier()
tree_clf = tree_clf.fit(X, y)
# and then plot the tree
tree.plot_tree(tree_clf)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Printing out as text
-Printing out as text
-
-
-Alternatively, the tree can also be exported in textual format with the function exporttext.
+
Alternatively, the tree can also be exported in textual format with the function exporttext.
This method doesn’t require the installation of external libraries and is more compact:
+
-
-
from sklearn.datasets import load_iris
+
+
+
+
+
+ from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
@@ -945,87 +1140,92 @@ decision_tree = DecisionTreeClassifier(rando
decision_tree = decision_tree.fit(iris.data, iris.target)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Algorithms for Setting up Decision Trees
-Algorithms for Setting up Decision Trees
-
-
-Two algorithms stand out in the set up of decision trees:
-
+
Two algorithms stand out in the set up of decision trees:
- The CART (Classification And Regression Tree) algorithm for both classification and regression
- The ID3 algorithm based on the computation of the information gain for classification
-
-We discuss both algorithms with applications here. The popular library
+We discuss both algorithms with applications here. The popular library
Scikit-Learn uses the CART algorithm. For classification problems
you can use either the gini index or the entropy to split a tree
in two branches.
+
-
+
The CART algorithm for Classification
-The CART algorithm for Classification
-
-
-For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \).
+
For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \).
This could be for example a threshold set by a number below a certain circumference of a malign tumor.
+
-
-How do we find these two quantities?
+
How do we find these two quantities?
We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \).
The cost function it tries to minimize is then
+
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
$$
-where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
+where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
is the number of instances in the left/right subset
+
-
-Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
+
Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the
\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other
hyperparameters control additional stopping conditions such as the \( min\_samples\_split \),
\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).
+
-
+
The CART algorithm for Regression
-The CART algorithm for Regression
-
-
-The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
+
The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now
+
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
$$
-Here the MSE for a specific node is defined as
+Here the MSE for a specific node is defined as
$$
\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
$$
-with
+with
$$
\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
$$
-the mean value of all observations in a specific node.
+the mean value of all observations in a specific node.
-
-Without any regularization, the regression task for decision trees,
+
Without any regularization, the regression task for decision trees,
just like for classification tasks, is prone to overfitting.
+
-
+
Computing the Gini index
-Computing the Gini index
-
-
-The example we will look at is a classical one in many Machine
+
The example we will look at is a classical one in many Machine
Learning applications. Based on various meteorological features, we
have several so-called attributes which decide whether we at the end
will do some outdoor activity like skiing, going for a bike ride etc
@@ -1035,10 +1235,10 @@ etc. The table here contains the feautures outlook, temperature,
attributes for each feature are then sunny, overcast and rain for the
outlook, hot, cold and mild for temperature, high and normal for
humidity and weak and strong for wind.
+
-
-The table here summarizes the various attributes and
-
+The table here summarizes the various attributes and
+
Day Outlook Temperature Humidity Wind Ride
@@ -1059,15 +1259,18 @@ The table here summarizes the various attributes and
14 Rain Mild High Strong 0
-
+
+
Simple Python Code to read in Data and perform Classification
-Simple Python Code to read in Data and perform Classification
-
-
-
# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -1134,25 +1337,41 @@ export_graphviz(
)
cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
os.system(cmd)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Computing the Gini Factor
-Computing the Gini Factor
-
-
-The above functions (gini, entropy and misclassification error) are
+
The above functions (gini, entropy and misclassification error) are
important components of the so-called CART algorithm. We will discuss
this algorithm below after we have discussed the information gain
algorithm ID3.
+
-
-In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.
+
In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.
-
-
# Split a dataset based on an attribute and an attribute value
+
+
+
+
+
+ # Split a dataset based on an attribute and an attribute value
def test_split(index, value, dataset):
left, right = list(), list()
for row in dataset:
@@ -1212,15 +1431,28 @@ dataset = [[0
split = get_split(dataset)
print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Entropy and the ID3 algorithm
-Entropy and the ID3 algorithm
-
-
-The ID3 algorithm learns decision trees by constructing
+
The ID3 algorithm learns decision trees by constructing
them in a top down way, beginning with the question which attribute should be tested at the root of the tree?
+
- Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
@@ -1230,33 +1462,34 @@ them in a top down way, beginning with the question which attribute should be
- The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
- This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
-
-The ID3 algorithm selects which attribute to test at each node in the
+The ID3 algorithm selects which attribute to test at each node in the
tree.
+
-
-We would like to select the attribute that is most useful for classifying
+
We would like to select the attribute that is most useful for classifying
examples.
+
-
-What is a good quantitative measure of the worth of an attribute?
+
What is a good quantitative measure of the worth of an attribute?
-
-Information gain measures how well a given attribute separates the
+
Information gain measures how well a given attribute separates the
training examples according to their target classification.
+
-
-The ID3 algorithm uses this information gain measure to select among the candidate
+
The ID3 algorithm uses this information gain measure to select among the candidate
attributes at each step while growing the tree.
+
-
-
-
Cancer Data again now with Decision Trees and other Methods
-
+
Cancer Data again now with Decision Trees and other Methods
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -1297,15 +1530,32 @@ svm.fit(X_train_scaled, y_train)
# 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)))
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Another example, the moons again
-
+
+
+
Another example, the moons again
-from __future__ import division, print_function, unicode_literals
+
+
+
+
+
+ from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
@@ -1369,15 +1619,32 @@ 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()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Playing around with regions
-
+
+
+
Playing around with regions
-np.random.seed(6)
+
+
+
+
+
+ np.random.seed(6)
Xs = np.random.rand(100, 2) - 0.5
ys = (Xs[:, 0] > 0).astype(np.float32) * 2
@@ -1397,37 +1664,86 @@ plt.subplot(122
plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Regression trees
-
+
+
+
Regression trees
-# Quadratic training set + noise
+
+
+
+
+
+ # 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
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-from sklearn.tree import DecisionTreeRegressor
+
+
+
+
+
+ from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
tree_reg.fit(X, y)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Final regressor code
-
+
+
+
Final regressor code
-from sklearn.tree import DecisionTreeRegressor
+
+
+
+
+
+ from sklearn.tree import DecisionTreeRegressor
tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
@@ -1465,11 +1781,26 @@ plt.text(0.3.title("max_depth=3", fontsize=14)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-tree_reg1 = DecisionTreeRegressor(random_state=42)
+
+
+
+
+
+ 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)
@@ -1497,11 +1828,24 @@ plt.xlabel(&quo
plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Pros and cons of trees, pros
+
+
+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)
@@ -1512,10 +1856,8 @@ plt.show()
- 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
+Disadvantages
- Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
@@ -1526,28 +1868,26 @@ plt.show()
- 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
+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
-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
+
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
+
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
+
- Voting classifiers
@@ -1555,50 +1895,45 @@ try to explain here. These are
- Random forests
- Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
+We discuss these methods here.
-We discuss these methods here.
-
-
+
An Overview of Ensemble Methods
-An Overview of Ensemble Methods
+
+
+
+
+
-
-

-
-
+
Bagging
-Bagging
-
-
-The plain decision trees suffer from high
+
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.
+of \( n \) to \( p \) is moderately large.
+
-
-Bootstrap aggregation, or just bagging, is a
+
Bootstrap aggregation, or just bagging, is a
general-purpose procedure for reducing the variance of a statistical
-learning method.
+learning method.
+
-
+
More bagging
-More bagging
-
-
-Bagging typically results in improved accuracy
+
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
+
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
@@ -1613,19 +1948,22 @@ 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.
+
-
+
Making your own Bootstrap: Changing the Level of the Decision Tree
-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
+
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 \)).
-
+
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
@@ -1676,69 +2014,81 @@ plt.plot(polydegree, variance, label.legend()
save_fig("baggingboot")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Why Voting?
-Why Voting?
-
-
-The idea behind boosting, and voting as well can be phrased as follows:
+
The idea behind boosting, and voting as well can be phrased as follows:
Can a group of people somehow arrive at highly
reasoned decisions, despite the weak judgement of the individual
members?
+
-
-The aim is to create a good classifier by combining several weak classifiers.
+
The aim is to create a good classifier by combining several weak classifiers.
A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.
+
-
-The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
+
The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in
-each iteration.
+each iteration.
+
-
-Decision trees play an important role as our weak classifier. They serve as the basic method.
+
Decision trees play an important role as our weak classifier. They serve as the basic method.
-
+
Tossing coins
-Tossing coins
-
-
-The simplest case is a so-called voting ensemble. To illustrate this,
+
The simplest case is a so-called voting ensemble. To illustrate this,
think of yourself tossing coins with a biased outcome of 51 per cent
for heads and 49% for tails. With only few tosses,
you may not clearly see this distribution for heads and tails. However, after some
thousands of tosses, there will be a clear majority of heads. With 2000 tosses
you should see approximately 1020 heads and 980 tails.
+
-
-We can then state that the outcome is a clear majority of heads. If
+
We can then state that the outcome is a clear majority of heads. If
you do this ten thousand times, it is easy to see that there is a 97%
likelihood of a majority of heads.
+
-
-Another example would be to collect all polls before an
+
Another example would be to collect all polls before an
election. Different polls may show different likelihoods for a
candidate winning with say a majority of the popular vote. The majority vote
would then consist in many polls indicating that this candidate will
actually win.
+
-
-The example here shows how we can implement the coin tossing case,
+
The example here shows how we can implement the coin tossing case,
clealry demostrating that after some tosses we see the law of large
numbers kicking in.
+
-
+
Standard imports first
-Standard imports first
-
-
-
# Common imports
+
+
+
+
+
+ # Common imports
from IPython.display import Image
from pydot import graph_from_dot_data
import pandas as pd
@@ -1775,15 +2125,32 @@ DATA_ID = "
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Simple Voting Example, head or tail
-
+
+
+
Simple Voting Example, head or tail
-# Common imports
+
+
+
+
+
+ # Common imports
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
@@ -1805,18 +2172,34 @@ plt.legend(loc=
plt.axis([0, 10000, 0.42, 0.58])
save_fig("votingsimple")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Using the Voting Classifier
-Using the Voting Classifier
-
-
-We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
-
+
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
-from sklearn.model_selection import train_test_split
+
+
+
+
+
+ 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)
@@ -1858,16 +2241,33 @@ voting_clf.fit(X_train, y_train)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Voting and Bagging
-Voting and Bagging
-
-
-
from sklearn.model_selection import train_test_split
+
+
+
+
+
+ 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)
@@ -1885,21 +2285,51 @@ 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
+
+
+
+
+
+ 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(random_state=42)
+
+
+
+
+
+ log_clf = LogisticRegression(random_state=42)
rnd_clf = RandomForestClassifier(random_state=42)
svm_clf = SVC(probability=True, random_state=42)
@@ -1907,49 +2337,76 @@ 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
+
+
+
+
+
+ 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))
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Random forests
-Random forests
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
-
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
-
-
-As in bagging, we build a
+
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.
+use only one of those \( m \) predictors.
+
-
-A fresh sample of \( m \) predictors is
+
A fresh sample of \( m \) predictors is
taken at each split, and typically we choose
+
$$
m\approx \sqrt{p}.
$$
-
-In building a random forest, at
+
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.
+a majority of the available predictors.
+
-
-The reason for this is rather clever. Suppose that there is one very
+
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
@@ -1961,41 +2418,36 @@ 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.
-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.
-
+
We will grow of forest of say \( B \) trees.
- For \( b=1:B \)
-
- Draw a bootstrap sample from the training data organized in our \( \boldsymbol{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
-
- we select \( m \le p \) variables at random from the \( p \) predictors/features
- pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
- split the node into daughter nodes
-
-
- 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
-
+
Random Forests Compared with other Methods on the Cancer Data
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2061,362 +2513,374 @@ skplt.metrics.<
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
-
-
-Recall that the cumulative gains curve shows the percentage of the
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Recall that the cumulative gains curve shows the percentage of the
overall number of cases in a given category gained by targeting a
percentage of the total number of cases.
+
-
-Similarly, the receiver operating characteristic curve, or ROC curve,
+
Similarly, the receiver operating characteristic curve, or ROC curve,
displays the diagnostic ability of a binary classifier system as its
discrimination threshold is varied. It plots the true positive rate against the false positive rate.
+
-
-
-
Compare Bagging on Trees with Random Forests
-
+
Compare Bagging on Trees with Random Forests
-bag_clf = BaggingClassifier(
+
+
+
+
+
+ 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)
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-bag_clf.fit(X_train, y_train)
+
+
+
+
+
+ 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)
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Boosting, a Bird's Eye View
-Boosting, a Bird's Eye View
-
-
-The basic idea is to combine weak classifiers in order to create a good
+
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
+
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
-What is boosting? Additive Modelling/Iterative Fitting
-
-
-Boosting is a way of fitting an additive expansion in a set of
+
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
+
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
-
-where \( \beta_m \) are the expansion parameters to be determined in a
+
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
+
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
+
$$
\sigma(t) = \frac{1}{1+\exp{(-t)}},
$$
-
-where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and
+
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
+
As another example, consider the cost function we defined for linear regression
$$
C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-In this case the function \( f(x) \) was replaced by the design matrix
+
In this case the function \( f(x) \) was replaced by the design matrix
\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \),
that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can
simply invert a matrix and obtain the parameters \( \beta \) by
+
$$
\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
-
-In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).
+
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
-Iterative Fitting, Regression and Squared-error Cost Function
-
-
-The way we proceed is as follows (here we specialize to the squared-error cost function)
+
The way we proceed is as follows (here we specialize to the squared-error cost function)
- Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
- Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
- For \( m=1:M \)
-
- minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
- This gives the optimal values \( \beta_m \) and \( \gamma_m \)
- 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
+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
-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.
-
-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 \).
-
-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
+
This means that for every iteration \( m \), we need to optimize
$$
(\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.
$$
-
-We start our iteration by simply setting \( f_0(x)=0 \).
+
We start our iteration by simply setting \( f_0(x)=0 \).
Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
+
$$
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
$$
-and
+and
$$
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
$$
-We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
+We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
$$
\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
$$
-which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
+which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
$$
\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
$$
-
-which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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.
+
which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{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 \).
+
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
-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
+
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
+
The error rate of the training sample is then
$$
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
$$
-
-The iterative procedure starts with defining a weak classifier whose
+
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
+
Here we will express our function \( f(x) \) in terms of \( G(x) \). That is
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
-will be a function of
+will be a function of
$$
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
$$
-
+
+
Adaptive Boosting, AdaBoost
-Adaptive Boosting, AdaBoost
-
-
-In our iterative procedure we define thus
+
In our iterative procedure we define thus
$$
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
$$
-
-The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
+
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
+
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
$$
-
-We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case.
+
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
+
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
$$
-where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
+where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
-
+
Building up AdaBoost
-Building up AdaBoost
-
-
-First, for any \( \beta > 0 \), we optimize \( G \) by setting
+
First, for any \( \beta > 0 \), we optimize \( G \) by setting
$$
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
$$
-which is the classifier that minimizes the weighted error rate in predicting \( y \).
+which is the classifier that minimizes the weighted error rate in predicting \( y \).
-
-We can do this by rewriting
+
We can do this by rewriting
$$
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
$$
-which can be rewritten as
+which can be rewritten as
$$
(\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,
$$
-which leads to
+which leads to
$$
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
$$
-where we have redefined the error as
+where we have redefined the error as
$$
\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},
$$
-which leads to an update of
+which leads to an update of
$$
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
$$
-This leads to the new weights
+This leads to the new weights
$$
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
$$
-
+
+
Adaptive boosting: AdaBoost, Basic Algorithm
-Adaptive boosting: AdaBoost, Basic Algorithm
-
-
-The algorithm here is rather straightforward. Assume that our weak
+
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
\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{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 \( \boldsymbol{y} \).
+classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \).
+
-
-We have already defined the misclassification error \( \mathrm{err} \) as
+
We have already defined the misclassification error \( \mathrm{err} \) as
$$
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
$$
-where the function \( I() \) is one if we misclassify and zero if we classify correctly.
+where the function \( I() \) is one if we misclassify and zero if we classify correctly.
-
+
Basic Steps of AdaBoost
-Basic Steps of AdaBoost
-
-
-With the above definitions we are now ready to set up the algorithm for 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.
-
+
- 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 \).
- We rewrite the misclassification error as
-
$$
\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},
$$
-
- 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.
-
- Fit then a given classifier to the training set using the weights \( w_i \).
- Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
- Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
- Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
-
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
+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
-AdaBoost Examples
+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-
-Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-
-
-
from sklearn.ensemble import AdaBoostClassifier
+
+
+
+
+
+ from sklearn.ensemble import AdaBoostClassifier
ada_clf = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1), n_estimators=200,
@@ -2437,114 +2901,115 @@ skplt.metrics.<
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-
-
-Gradient boosting is again a similar technique to Adaptive boosting,
+
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
+
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
-The Squared-Error again! Steepest Descent
-
-
-We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
+
We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
This means that for every iteration, we need to optimize
+
$$
(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
+
We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
$$
f_M(x) = \sum_{m=0}^M h_m(x).
$$
-
-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
+
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
$$
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)}.
$$
-
-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
+
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
+
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
$$
(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
$$
-
+
+
Steepest Descent Example
-Steepest Descent Example
-
-
-Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
+
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
$$
f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
$$
-We can then proceed and compute
+We can then proceed and compute
$$
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,
$$
-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.
+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
-Gradient Boosting, algorithm
-
-
-Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
+
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
so we do not learn a function that can generalize. However, we can modify the algorithm by
-fitting a weak learner to approximate the negative gradient signal.
+fitting a weak learner to approximate the negative gradient signal.
+
-
-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
+
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
$$
C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
-
-The way we proceed in an iterative fashion is to
-
+
The way we proceed in an iterative fashion is to
- Initialize our estimate \( f_0(x) \).
- For \( m=1:M \), we
-
- compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
- fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
- update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
-
The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
-
-
-Gradient Boosting, Examples of Regression
-
+
Gradient Boosting, Examples of Regression
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
@@ -2590,15 +3055,32 @@ plt.plot(polydegree, variance, label.legend()
save_fig("gdregression")
plt.show()
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-Gradient Boosting, Classification Example
-
+
+
+
Gradient Boosting, Classification Example
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2638,37 +3120,51 @@ plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
save_fig("gdclassiffiercgain")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+XGBoost: Extreme Gradient Boosting
-XGBoost: Extreme Gradient Boosting
-
-
-XGBoost or Extreme Gradient
+
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.
+
-
-The authors design and build a highly scalable end-to-end tree
+
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!!!
+
It is now the algorithm which wins essentially all ML competitions!!!
-
+
Regression Case
-Regression Case
-
-
-
import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import xgboost as xgb
@@ -2714,18 +3210,34 @@ plt.plot(polydegree, bias, label.plot(polydegree, variance, label='Variance')
plt.legend()
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Xgboost on the Cancer Data
-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.
-
+
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.
-import matplotlib.pyplot as plt
+
+
+
+
+
+ import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
@@ -2776,18 +3288,26 @@ xgb.plot_importance(xg_clf)
plt.rcParams['figure.figsize'] = [5, 5]
save_fig("xgparams")
plt.show()
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
© 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
-
-
-
diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz
index 4a2660273..89adf4908 100644
Binary files a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ
diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb
index 9cd96210c..a77c21c23 100644
--- a/doc/pub/week45/ipynb/week45.ipynb
+++ b/doc/pub/week45/ipynb/week45.ipynb
@@ -2,8 +2,7 @@
"cells": [
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "5029effd",
+ "id": "9b8dfaf4",
"metadata": {
"editable": true
},
@@ -15,21 +14,14 @@
},
{
"cell_type": "markdown",
- "id": "0a3a2ca8",
+ "id": "bf39b58b",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
- "\n",
"# Week 45: Decisions Trees, Random Forests, Bagging and Boosting\n",
- "\n",
- " \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
-<<<<<<< HEAD
"Date: **Nov 11, 2021**\n",
"\n",
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license"
@@ -37,19 +29,11 @@
},
{
"cell_type": "markdown",
- "id": "01543c43",
+ "id": "91ca8a85",
"metadata": {
"editable": true
},
"source": [
-=======
- "Date: **Nov 10, 2021**\n",
- "\n",
- "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Overview of week 45\n",
"\n",
"* Thursday: Basics of Decision Trees, Bagging and Voting\n",
@@ -62,31 +46,20 @@
"\n",
"[Video on boosting methods by Hastie](https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai).\n",
"\n",
- "\n",
- "\n",
"**Reading.**\n",
"\n",
-<<<<<<< HEAD
"1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion."
]
},
{
"cell_type": "markdown",
- "id": "57a03129",
+ "id": "1d9c3ff5",
"metadata": {
"editable": true
},
"source": [
-=======
- "1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion.\n",
- "\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Decision trees, overarching aims\n",
"\n",
- "\n",
"We start here with the most basic algorithm, the so-called decision\n",
"tree. With this basic algorithm we can in turn build more complex\n",
"networks, spanning from homogeneous and heterogenous forests (bagging,\n",
@@ -97,7 +70,6 @@
"Decision trees are supervised learning algorithms used for both,\n",
"classification and regression tasks.\n",
"\n",
- "\n",
"The main idea of decision trees\n",
"is to find those descriptive features which contain the most\n",
"**information** regarding the target feature and then split the dataset\n",
@@ -107,21 +79,16 @@
"The descriptive features which reproduce best the target/output features are normally said\n",
"to be the most informative ones. The process of finding the **most\n",
"informative** feature is done until we accomplish a stopping criteria\n",
-<<<<<<< HEAD
"where we then finally end up in so called **leaf nodes**."
]
},
{
"cell_type": "markdown",
- "id": "62b1b891",
+ "id": "1a12ccc6",
"metadata": {
"editable": true
},
"source": [
-=======
- "where we then finally end up in so called **leaf nodes**. \n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Basics of a tree\n",
"\n",
"A decision tree is typically divided into a **root node**, the **interior nodes**,\n",
@@ -132,13 +99,12 @@
"to our trained model. This is possible since the model has \n",
"learned the underlying structure of the training data and hence can,\n",
"given some assumptions, make predictions about the target feature value\n",
-<<<<<<< HEAD
"(class) of unseen query instances."
]
},
{
"cell_type": "markdown",
- "id": "b58e96f8",
+ "id": "1526c923",
"metadata": {
"editable": true
},
@@ -150,7 +116,7 @@
},
{
"cell_type": "markdown",
- "id": "e98d1b92",
+ "id": "1099be1a",
"metadata": {
"editable": true
},
@@ -162,55 +128,29 @@
},
{
"cell_type": "markdown",
- "id": "b36bc042",
+ "id": "90d02d50",
"metadata": {
"editable": true
},
"source": [
-=======
- "(class) of unseen query instances.\n",
- "\n",
- "## A Sketch of a Tree, Regression problem\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## A Sketch of a Tree, Classification problem\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## A typical Decision Tree with its pertinent Jargon, Classification Problem\n",
"\n",
"\n",
"\n",
"\n",
- "\n",
- "
\n",
- "\n",
+ "
Figure 1:
\n",
"\n",
"\n",
-<<<<<<< HEAD
"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."
]
},
{
"cell_type": "markdown",
- "id": "6182dd01",
+ "id": "df7a2494",
"metadata": {
"editable": true
},
"source": [
-=======
- "\n",
- "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.\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## General Features\n",
"\n",
"The overarching approach to decision trees is a top-down approach.\n",
@@ -224,25 +164,18 @@
"* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n",
"\n",
"This process is then repeated for the subtree rooted at the new\n",
-<<<<<<< HEAD
"node."
]
},
{
"cell_type": "markdown",
- "id": "4474c135",
+ "id": "6753134a",
"metadata": {
"editable": true
},
"source": [
-=======
- "node.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## How do we set it up?\n",
"\n",
- "\n",
"In simplified terms, the process of training a decision tree and\n",
"predicting the target features of query instances is as follows:\n",
"\n",
@@ -254,37 +187,26 @@
"\n",
"4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n",
"\n",
-<<<<<<< HEAD
"Then we are essentially done!"
]
},
{
"cell_type": "markdown",
- "id": "938cfbf4",
+ "id": "46ffd343",
"metadata": {
"editable": true
},
"source": [
-=======
- "Then we are essentially done!\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Decision trees and Regression"
]
},
{
"cell_type": "code",
"execution_count": 1,
-<<<<<<< HEAD
- "id": "fcfdb3ca",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "1ebcbcc3",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -382,14 +304,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d06f81d0",
+ "id": "cf342d57",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Building a tree, regression\n",
"\n",
@@ -408,14 +326,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "30987ca1",
+ "id": "aac615b9",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n",
@@ -424,8 +338,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "973f1d0b",
+ "id": "8c079fbe",
"metadata": {
"editable": true
},
@@ -436,18 +349,11 @@
},
{
"cell_type": "markdown",
- "id": "1c6d8f1d",
+ "id": "3e28385b",
"metadata": {
"editable": true
},
"source": [
-=======
- "metadata": {},
- "source": [
- "where $\\overline{y}_{R_j}$ is the mean response for the training observations \n",
- "within box $j$. \n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## A top-down approach, recursive binary splitting\n",
"\n",
"Unfortunately, it is computationally infeasible to consider every\n",
@@ -460,21 +366,16 @@
"further down on the tree. It is greedy because at each step of the\n",
"tree-building process, the best split is made at that particular step,\n",
"rather than looking ahead and picking a split that will lead to a\n",
-<<<<<<< HEAD
"better tree in some future step."
]
},
{
"cell_type": "markdown",
- "id": "f2d05d9e",
+ "id": "2c45d4e7",
"metadata": {
"editable": true
},
"source": [
-=======
- "better tree in some future step.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Making a tree\n",
"\n",
"In order to implement the recursive binary splitting we start by selecting\n",
@@ -483,14 +384,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f43f1d0c",
+ "id": "4c4ed2cb",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\left\\{X\\vert x_j < s\\right\\},\n",
@@ -499,28 +396,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "5a522921",
+ "id": "49b1cc90",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"and"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "61aac4b3",
+ "id": "c32c28c7",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\left\\{X\\vert x_j \\geq s\\right\\},\n",
@@ -529,28 +418,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "0ff01949",
+ "id": "23f260a1",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"so that we obtain the lowest MSE, that is"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1fae0428",
+ "id": "b7c08bc0",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\sum_{i:x_i\\in R_j}(y_i-\\overline{y}_{R_1})^2+\\sum_{i:x_i\\in R_2}(y_i-\\overline{y}_{R_2})^2,\n",
@@ -559,14 +440,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "92da3ee2",
+ "id": "a679d1e3",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which we want to minimize by considering all predictors\n",
"$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n",
@@ -591,22 +468,16 @@
"have three regions. Again, we look to split one of these three regions\n",
"further, so as to minimize the MSE. The process continues until a\n",
"stopping criterion is reached; for instance, we may continue until no\n",
-<<<<<<< HEAD
"region contains more than five observations."
]
},
{
"cell_type": "markdown",
- "id": "4452e6cb",
+ "id": "44dd0c2c",
"metadata": {
"editable": true
},
"source": [
-=======
- "region contains more than five observations.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Pruning the tree\n",
"\n",
"The above procedure is rather straightforward, but leads often to\n",
@@ -621,21 +492,16 @@
"we consider a sequence of trees indexed by a nonnegative tuning\n",
"parameter $\\alpha$.\n",
"\n",
-<<<<<<< HEAD
"Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py)."
]
},
{
"cell_type": "markdown",
- "id": "9884a7e6",
+ "id": "18f923eb",
"metadata": {
"editable": true
},
"source": [
-=======
- "Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py).\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Cost complexity pruning\n",
"\n",
"For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that"
@@ -643,14 +509,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "c8edb67c",
+ "id": "f2e293a5",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n",
@@ -659,14 +521,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "4e7213ce",
+ "id": "fc2583b1",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"is as small as possible. Here $\\overline{T}$ is \n",
"the number of terminal nodes of the tree $T$ , $R_m$ is the\n",
@@ -681,33 +539,25 @@
"having a tree with many terminal nodes. The above equation will\n",
"tend to be minimized for a smaller subtree. \n",
"\n",
- "\n",
"It turns out that as we increase $\\alpha$ from zero\n",
"branches get pruned from the tree in a nested and predictable fashion,\n",
"so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n",
"easy. We can select a value of $\\alpha$ using a validation set or using\n",
"cross-validation. We then return to the full data set and obtain the\n",
-<<<<<<< HEAD
"subtree corresponding to $\\alpha$."
]
},
{
"cell_type": "markdown",
- "id": "52c4e553",
+ "id": "5ff854e9",
"metadata": {
"editable": true
},
"source": [
-=======
- "subtree corresponding to $\\alpha$. \n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Schematic Regression Procedure\n",
"\n",
"**Building a Regression Tree.**\n",
"\n",
- "\n",
"1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n",
"\n",
"2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n",
@@ -720,25 +570,16 @@
"\n",
" * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n",
"\n",
-<<<<<<< HEAD
"4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$."
]
},
{
"cell_type": "markdown",
- "id": "b8b0003f",
+ "id": "d9c1302e",
"metadata": {
"editable": true
},
"source": [
-=======
- "\n",
- "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$.\n",
- "\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## A Classification Tree\n",
"\n",
"A classification tree is very similar to a regression tree, except\n",
@@ -752,21 +593,16 @@
"classification tree, we are often interested not only in the class\n",
"prediction corresponding to a particular terminal node region, but\n",
"also in the class proportions among the training observations that\n",
-<<<<<<< HEAD
"fall into that region."
]
},
{
"cell_type": "markdown",
- "id": "da726ea4",
+ "id": "205f4fdc",
"metadata": {
"editable": true
},
"source": [
-=======
- "fall into that region. \n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Growing a classification tree\n",
"\n",
"The task of growing a\n",
@@ -784,22 +620,16 @@
"When building a classification tree, either the Gini index or the\n",
"entropy are typically used to evaluate the quality of a particular\n",
"split, since these two approaches are more sensitive to node purity\n",
-<<<<<<< HEAD
"than is the classification error rate."
]
},
{
"cell_type": "markdown",
- "id": "1ca80d94",
+ "id": "a1ad5668",
"metadata": {
"editable": true
},
"source": [
-=======
- "than is the classification error rate. \n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Classification tree, how to split nodes\n",
"\n",
"If our targets are the outcome of a classification process that takes\n",
@@ -814,14 +644,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f7caed93",
+ "id": "5adaf1c8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"p_{mk} = \\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i=k).\n",
@@ -830,14 +656,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f810cd2b",
+ "id": "d06ca754",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We let $p_{mk}$ represent the majority class of observations in region\n",
"$m$. The three most common ways of splitting a node are given by\n",
@@ -847,14 +669,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "a99accde",
+ "id": "cb0de517",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n",
@@ -863,28 +681,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "70f12422",
+ "id": "b7fbccc8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"* Gini index $g$"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "2c764a1f",
+ "id": "d349afd4",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"g = \\sum_{k\\ne k'} p_{mk}p_{mk'}=\\sum_{k=1}^K p_{mk}(1-p_{mk}).\n",
@@ -893,28 +703,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "36ce64fd",
+ "id": "818a2976",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"* Information entropy or just entropy $s$"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "c7cdc315",
+ "id": "bb44896f",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n",
@@ -923,13 +725,12 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "6f9b611a",
+ "id": "3babbf3b",
"metadata": {
"editable": true
},
"source": [
- "## Gini Index?Coefficient/Impurity\n",
+ "## Gini Index (or Coefficient or Impurity)\n",
"\n",
"The Gini index $g$ gives us the degree of probability of a specific\n",
"variable that is wrongly classified.\n",
@@ -946,12 +747,12 @@
},
{
"cell_type": "markdown",
- "id": "5afd0691",
+ "id": "e0401980",
"metadata": {
"editable": true
},
"source": [
- "## Why binary split?\n",
+ "## Why binary splits?\n",
"\n",
"It is custom to split to a tree uising binary splits. The reason is\n",
"that multiway splits fragment the data too quickly, leaving\n",
@@ -961,13 +762,93 @@
},
{
"cell_type": "markdown",
- "id": "75295fdc",
+ "id": "ee7099d5",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Computing a Tree using the Gini Index\n",
+ "\n",
+ "Consider the following example with attributes/features and two\n",
+ "possible outcomes (classes) for each attribute. Assume we wish to find some\n",
+ "correlations between the average grade of a student as function of the\n",
+ "number of hours studied and hours slept. We want also to correlate the\n",
+ "grade in a given course with the general trend, whether the students\n",
+ "recently has gotten grades below average or above.\n",
+ "\n",
+ "We have three features/attributes\n",
+ "1. Trend of average grades before present course, classified as either below or above the average grade of the whole class \n",
+ "\n",
+ "2. The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one $ECTS$ which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester. \n",
+ "\n",
+ "3. The number of hours slept as high for more than $8$ hours and below for less than 8 hours of sleep, classified again as either high or low\n",
+ "\n",
+ "4. The final grade whether it is above or below average"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "23281cd5",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## The Table\n",
+ "\n",
+ "\n",
+ "\n",
+ "Grade Trend Hours slept Hours Studied Grade \n",
+ "\n",
+ "\n",
+ "\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70f23559",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Computing the various Gini Indices\n",
+ "\n",
+ "In computations we will translate all classes into numbers. Being\n",
+ "these binary classes, they can easily be split into ones and zeros.\n",
+ "\n",
+ "**Gini index for Average trend.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8b92a015",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Computing the various Gini Indices, Hours slept\n",
+ "\n",
+ "**Gini index for hour slept.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "568d0490",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Computing the various Gini Indices, Hours studied\n",
+ "\n",
+ "**Gini index for hour studied.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f293a7e7",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Visualizing the Tree, Classification"
]
@@ -975,12 +856,10 @@
{
"cell_type": "code",
"execution_count": 2,
-<<<<<<< HEAD
- "id": "4b5e8fd0",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "b13a3419",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1021,14 +900,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "2a7a2bc3",
+ "id": "f1128ce7",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Visualizing the Tree, The Moons"
]
@@ -1036,12 +911,10 @@
{
"cell_type": "code",
"execution_count": 3,
-<<<<<<< HEAD
- "id": "404b6b46",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "0fb25088",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1073,14 +946,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "fa63b030",
+ "id": "d27d2389",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Other ways of visualizing the trees\n",
"\n",
@@ -1090,12 +959,10 @@
{
"cell_type": "code",
"execution_count": 4,
-<<<<<<< HEAD
- "id": "e18305d7",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "861e062f",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1110,14 +977,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d3c9b005",
+ "id": "6b0470a8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Printing out as text\n",
"\n",
@@ -1128,12 +991,10 @@
{
"cell_type": "code",
"execution_count": 5,
-<<<<<<< HEAD
- "id": "b975a14b",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "332ac25d",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1149,14 +1010,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "99f98c77",
+ "id": "05a4924e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Algorithms for Setting up Decision Trees\n",
"\n",
@@ -1168,21 +1025,16 @@
"We discuss both algorithms with applications here. The popular library\n",
"**Scikit-Learn** uses the CART algorithm. For classification problems\n",
"you can use either the **gini** index or the **entropy** to split a tree\n",
-<<<<<<< HEAD
"in two branches."
]
},
{
"cell_type": "markdown",
- "id": "272a7e38",
+ "id": "8c3c04b4",
"metadata": {
"editable": true
},
"source": [
-=======
- "in two branches.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## The CART algorithm for Classification\n",
"\n",
"For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$.\n",
@@ -1195,14 +1047,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "e413c33c",
+ "id": "3a7ee742",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n",
@@ -1211,14 +1059,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "942dab79",
+ "id": "9eac9045",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n",
" is the number of instances in the left/right subset\n",
@@ -1227,21 +1071,16 @@
"and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n",
"$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n",
"hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n",
-<<<<<<< HEAD
"$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$."
]
},
{
"cell_type": "markdown",
- "id": "92fb5cd3",
+ "id": "e1c713ab",
"metadata": {
"editable": true
},
"source": [
-=======
- "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## The CART algorithm for Regression\n",
"\n",
"The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the\n",
@@ -1250,14 +1089,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f9d1aa8e",
+ "id": "fe2facef",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n",
@@ -1266,28 +1101,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "26b91b6f",
+ "id": "d634ab72",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"Here the MSE for a specific node is defined as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "7ce65e73",
+ "id": "74687001",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n",
@@ -1296,28 +1123,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "396e79d5",
+ "id": "2a9e7db6",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"with"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "396f74b5",
+ "id": "d594c20a",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n",
@@ -1326,34 +1145,24 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "4cbe3954",
+ "id": "0e43bfd3",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"the mean value of all observations in a specific node.\n",
"\n",
"Without any regularization, the regression task for decision trees, \n",
-<<<<<<< HEAD
"just like for classification tasks, is prone to overfitting."
]
},
{
"cell_type": "markdown",
- "id": "5f491d9d",
+ "id": "29134276",
"metadata": {
"editable": true
},
"source": [
-=======
- "just like for classification tasks, is prone to overfitting.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Computing the Gini index\n",
"\n",
"The example we will look at is a classical one in many Machine\n",
@@ -1368,7 +1177,7 @@
"humidity and weak and strong for wind.\n",
"\n",
"The table here summarizes the various attributes and\n",
- "\n",
+ "\n",
"\n",
"Day Outlook Temperature Humidity Wind Ride \n",
"\n",
@@ -1388,33 +1197,26 @@
" 13 Overcast Hot Normal Weak 1 \n",
" 14 Rain Mild High Strong 0 \n",
"\n",
-<<<<<<< HEAD
"
"
]
},
{
"cell_type": "markdown",
- "id": "ba9449d2",
+ "id": "4c0d3c83",
"metadata": {
"editable": true
},
"source": [
-=======
- "
\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Simple Python Code to read in Data and perform Classification"
]
},
{
"cell_type": "code",
"execution_count": 6,
-<<<<<<< HEAD
- "id": "ddcfa964",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "ad8af3c3",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1489,14 +1291,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f8a112fa",
+ "id": "d2ab77bc",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Computing the Gini Factor\n",
"\n",
@@ -1511,12 +1309,10 @@
{
"cell_type": "code",
"execution_count": 7,
-<<<<<<< HEAD
- "id": "bd14f8fd",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "153ca45c",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1584,14 +1380,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "b02c63b6",
+ "id": "f39506fe",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Entropy and the ID3 algorithm\n",
"\n",
@@ -1622,34 +1414,26 @@
"training examples according to their target classification.\n",
"\n",
"The ID3 algorithm uses this information gain measure to select among the candidate\n",
-<<<<<<< HEAD
"attributes at each step while growing the tree."
]
},
{
"cell_type": "markdown",
- "id": "be4068bc",
+ "id": "14b28d3f",
"metadata": {
"editable": true
},
"source": [
-=======
- "attributes at each step while growing the tree.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Cancer Data again now with Decision Trees and other Methods"
]
},
{
"cell_type": "code",
"execution_count": 8,
-<<<<<<< HEAD
- "id": "37fe4589",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "c9bb625f",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1698,14 +1482,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "7f22a1b7",
+ "id": "eff761eb",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Another example, the moons again"
]
@@ -1713,12 +1493,10 @@
{
"cell_type": "code",
"execution_count": 9,
-<<<<<<< HEAD
- "id": "319313ce",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "8030254f",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1790,14 +1568,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "db1e37fc",
+ "id": "8d691d6e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Playing around with regions"
]
@@ -1805,12 +1579,10 @@
{
"cell_type": "code",
"execution_count": 10,
-<<<<<<< HEAD
- "id": "3cb94475",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "de40ec78",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1838,14 +1610,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "e93f2813",
+ "id": "4d3ad5e4",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Regression trees"
]
@@ -1853,12 +1621,10 @@
{
"cell_type": "code",
"execution_count": 11,
-<<<<<<< HEAD
- "id": "87026915",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "6fd1d8f0",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1873,12 +1639,10 @@
{
"cell_type": "code",
"execution_count": 12,
-<<<<<<< HEAD
- "id": "9237d8d5",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "b2f072cf",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1890,14 +1654,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ee857f99",
+ "id": "6d514183",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Final regressor code"
]
@@ -1905,12 +1665,10 @@
{
"cell_type": "code",
"execution_count": 13,
-<<<<<<< HEAD
- "id": "379a7a94",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "36faaea6",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1957,12 +1715,10 @@
{
"cell_type": "code",
"execution_count": 14,
-<<<<<<< HEAD
- "id": "4030920d",
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "862941e5",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -1998,14 +1754,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "18f7ece2",
+ "id": "b5e1fd28",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Pros and cons of trees, pros\n",
"\n",
@@ -2021,21 +1773,16 @@
"\n",
"* Can model interactions between the different descriptive features\n",
"\n",
-<<<<<<< HEAD
"* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)"
]
},
{
"cell_type": "markdown",
- "id": "97a1b36e",
+ "id": "20523962",
"metadata": {
"editable": true
},
"source": [
-=======
- "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Disadvantages\n",
"\n",
"* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
@@ -2054,22 +1801,16 @@
"\n",
"However, by aggregating many decision trees, using methods like\n",
"bagging, random forests, and boosting, the predictive performance of\n",
-<<<<<<< HEAD
"trees can be substantially improved."
]
},
{
"cell_type": "markdown",
- "id": "e6d882aa",
+ "id": "8865c78e",
"metadata": {
"editable": true
},
"source": [
-=======
- "trees can be substantially improved.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n",
"\n",
"As stated above and seen in many of the examples discussed here about\n",
@@ -2091,49 +1832,32 @@
"\n",
"4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n",
"\n",
-<<<<<<< HEAD
"We discuss these methods here."
]
},
{
"cell_type": "markdown",
- "id": "5551b560",
+ "id": "c5df92f2",
"metadata": {
"editable": true
},
"source": [
-=======
- "We discuss these methods here.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## An Overview of Ensemble Methods\n",
"\n",
"\n",
"\n",
"\n",
-<<<<<<< HEAD
"
Figure 1:
\n",
""
]
},
{
"cell_type": "markdown",
- "id": "21dc0297",
+ "id": "351916e4",
"metadata": {
"editable": true
},
"source": [
-=======
- "\n",
- "
\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Bagging\n",
"\n",
"The **plain** decision trees suffer from high\n",
@@ -2146,22 +1870,16 @@
"\n",
"**Bootstrap aggregation**, or just **bagging**, is a\n",
"general-purpose procedure for reducing the variance of a statistical\n",
-<<<<<<< HEAD
"learning method."
]
},
{
"cell_type": "markdown",
- "id": "e65838e4",
+ "id": "df75832e",
"metadata": {
"editable": true
},
"source": [
-=======
- "learning method. \n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## More bagging\n",
"\n",
"Bagging typically results in improved accuracy\n",
@@ -2184,307 +1902,16 @@
"trees. A large value indicates an important predictor. Similarly, in\n",
"the context of bagging classification trees, we can add up the total\n",
"amount that the Gini index is decreased by splits over a given\n",
-<<<<<<< HEAD
"predictor, averaged over all $B$ trees."
]
},
{
"cell_type": "markdown",
- "id": "cf464522",
+ "id": "291e724d",
"metadata": {
"editable": true
},
"source": [
- "## Simple Voting Example, head or tail"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "id": "9d03d9ba",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "heads_proba = 0.51\n",
- "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n",
- "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n",
- "plt.figure(figsize=(8,3.5))\n",
- "plt.plot(cumulative_heads_ratio)\n",
- "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n",
- "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n",
- "plt.xlabel(\"Number of coin tosses\")\n",
- "plt.ylabel(\"Heads ratio\")\n",
- "plt.legend(loc=\"lower right\")\n",
- "plt.axis([0, 10000, 0.42, 0.58])\n",
- "save_fig(\"votingsimple\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "eaff6b2f",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Using the Voting Classifier"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "id": "50de3ca5",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.datasets import make_moons\n",
- "\n",
- "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
- "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
- "\n",
- "from sklearn.ensemble import RandomForestClassifier\n",
- "from sklearn.ensemble import VotingClassifier\n",
- "from sklearn.linear_model import LogisticRegression\n",
- "from sklearn.svm import SVC\n",
- "\n",
- "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
- "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
- "svm_clf = SVC(gamma=\"auto\", random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='hard')\n",
-=======
- "predictor, averaged over all $B$ trees.\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
- "\n",
- "\n",
- "\n",
-<<<<<<< HEAD
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='soft')\n",
- "voting_clf.fit(X_train, y_train)\n",
- "\n",
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6910515b",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Please, not the moons again! Voting and Bagging"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "id": "37266fb4",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.datasets import make_moons\n",
- "\n",
- "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
- "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
- "from sklearn.ensemble import RandomForestClassifier\n",
- "from sklearn.ensemble import VotingClassifier\n",
- "from sklearn.linear_model import LogisticRegression\n",
- "from sklearn.svm import SVC\n",
- "\n",
- "log_clf = LogisticRegression(random_state=42)\n",
- "rnd_clf = RandomForestClassifier(random_state=42)\n",
- "svm_clf = SVC(random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='hard')\n",
- "voting_clf.fit(X_train, y_train)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "id": "4e3e7e4b",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "id": "84fb433e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "log_clf = LogisticRegression(random_state=42)\n",
- "rnd_clf = RandomForestClassifier(random_state=42)\n",
- "svm_clf = SVC(probability=True, random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='soft')\n",
- "voting_clf.fit(X_train, y_train)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "id": "657d10e9",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "83de8cfa",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Bagging Examples"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "id": "2e82fca3",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.ensemble import BaggingClassifier\n",
- "from sklearn.tree import DecisionTreeClassifier\n",
- "\n",
- "bag_clf = BaggingClassifier(\n",
- " DecisionTreeClassifier(random_state=42), n_estimators=500,\n",
- " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n",
- "bag_clf.fit(X_train, y_train)\n",
- "y_pred = bag_clf.predict(X_test)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "id": "7a1c6024",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "print(accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "id": "305e8fb0",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "tree_clf = DecisionTreeClassifier(random_state=42)\n",
- "tree_clf.fit(X_train, y_train)\n",
- "y_pred_tree = tree_clf.predict(X_test)\n",
- "print(accuracy_score(y_test, y_pred_tree))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "id": "09e1e925",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from matplotlib.colors import ListedColormap\n",
- "\n",
- "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n",
- " x1s = np.linspace(axes[0], axes[1], 100)\n",
- " x2s = np.linspace(axes[2], axes[3], 100)\n",
- " x1, x2 = np.meshgrid(x1s, x2s)\n",
- " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
- " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
- " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
- " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
- " if contour:\n",
- " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
- " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
- " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n",
- " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n",
- " plt.axis(axes)\n",
- " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
- " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
- "plt.figure(figsize=(11,4))\n",
- "plt.subplot(121)\n",
- "plot_decision_boundary(tree_clf, X, y)\n",
- "plt.title(\"Decision Tree\", fontsize=14)\n",
- "plt.subplot(122)\n",
- "plot_decision_boundary(bag_clf, X, y)\n",
- "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n",
- "save_fig(\"baggingtree\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c93add72",
- "metadata": {
- "editable": true
- },
- "source": [
-=======
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Making your own Bootstrap: Changing the Level of the Decision Tree\n",
"\n",
"Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n",
@@ -2493,14 +1920,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 25,
- "id": "a87db197",
-=======
"execution_count": 15,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "c83f0184",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2560,14 +1984,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "bd224b9b",
+ "id": "f7d9dc90",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Why Voting?\n",
"\n",
@@ -2583,21 +2003,16 @@
"In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in\n",
"each iteration. \n",
"\n",
-<<<<<<< HEAD
"Decision trees play an important role as our weak classifier. They serve as the basic method."
]
},
{
"cell_type": "markdown",
- "id": "0905f7fd",
+ "id": "2609f22e",
"metadata": {
"editable": true
},
"source": [
-=======
- "Decision trees play an important role as our weak classifier. They serve as the basic method. \n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Tossing coins\n",
"\n",
"The simplest case is a so-called voting ensemble. To illustrate this,\n",
@@ -2619,34 +2034,26 @@
"\n",
"The example here shows how we can implement the coin tossing case,\n",
"clealry demostrating that after some tosses we see the [law of large](https://en.wikipedia.org/wiki/Law_of_large_numbers)\n",
-<<<<<<< HEAD
"numbers kicking in."
]
},
{
"cell_type": "markdown",
- "id": "83e0c000",
+ "id": "97b04d9f",
"metadata": {
"editable": true
},
"source": [
-=======
- "numbers kicking in.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Standard imports first"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 26,
- "id": "46fedf6a",
-=======
"execution_count": 16,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "58866a66",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2691,28 +2098,21 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "c5b88629",
+ "id": "174163d8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Simple Voting Example, head or tail"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 27,
- "id": "cd753289",
-=======
"execution_count": 17,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "4420e743",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2743,14 +2143,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ff2c01f5",
+ "id": "8983614f",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Using the Voting Classifier\n",
"\n",
@@ -2759,14 +2155,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 28,
- "id": "5d722d0a",
-=======
"execution_count": 18,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "7a077945",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2816,28 +2209,21 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "8882a66e",
+ "id": "069325d3",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Voting and Bagging"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 29,
- "id": "23939bf2",
-=======
"execution_count": 19,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "0ea1ee6d",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2863,14 +2249,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 30,
- "id": "41bc3004",
-=======
"execution_count": 20,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "0a16628e",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2884,14 +2267,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 31,
- "id": "9d3397a2",
-=======
"execution_count": 21,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "da0476e7",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2907,14 +2287,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 32,
- "id": "6087fac8",
-=======
"execution_count": 22,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "29b9e12b",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -2928,14 +2305,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "94e1f957",
+ "id": "d1e069f5",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Random forests\n",
"\n",
@@ -2955,14 +2328,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1431c18a",
+ "id": "f1b4c46e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"m\\approx \\sqrt{p}.\n",
@@ -2971,14 +2340,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "2a5dfd06",
+ "id": "621a1fd2",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"In building a random forest, at\n",
"each split in the tree, the algorithm is not even allowed to consider\n",
@@ -2995,22 +2360,16 @@
"lead to as large of a reduction in variance as averaging many\n",
"uncorrelated quantities. In particular, this means that bagging will\n",
"not lead to a substantial reduction in variance over a single tree in\n",
-<<<<<<< HEAD
"this setting."
]
},
{
"cell_type": "markdown",
- "id": "00c72d63",
+ "id": "5730efd6",
"metadata": {
"editable": true
},
"source": [
-=======
- "this setting.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Random Forest Algorithm\n",
"The algorithm described here can be applied to both classification and regression problems.\n",
"\n",
@@ -3027,36 +2386,26 @@
"\n",
"3. split the node into daughter nodes\n",
"\n",
-<<<<<<< HEAD
"4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem."
]
},
{
"cell_type": "markdown",
- "id": "2e412e12",
+ "id": "8bdcabf9",
"metadata": {
"editable": true
},
"source": [
-=======
- "\n",
- "\n",
- "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem. \n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Random Forests Compared with other Methods on the Cancer Data"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 33,
- "id": "cf7ad4d8",
-=======
"execution_count": 23,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "27236fb8",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -3130,14 +2479,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "322bcada",
+ "id": "7481bf32",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"Recall that the cumulative gains curve shows the percentage of the\n",
"overall number of cases in a given category *gained* by targeting a\n",
@@ -3145,35 +2490,26 @@
"\n",
"Similarly, the receiver operating characteristic curve, or ROC curve,\n",
"displays the diagnostic ability of a binary classifier system as its\n",
-<<<<<<< HEAD
"discrimination threshold is varied. It plots the true positive rate against the false positive rate."
]
},
{
"cell_type": "markdown",
- "id": "26c6739a",
+ "id": "8c2d169d",
"metadata": {
"editable": true
},
"source": [
-=======
- "discrimination threshold is varied. It plots the true positive rate against the false positive rate.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Compare Bagging on Trees with Random Forests"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 34,
- "id": "729bb490",
-=======
"execution_count": 24,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "e1d18ed0",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -3184,14 +2520,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 35,
- "id": "8e9c400f",
-=======
"execution_count": 25,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "a5d9c257",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -3206,14 +2539,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "dd160607",
+ "id": "59e24e9e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Boosting, a Bird's Eye View\n",
"\n",
@@ -3225,22 +2554,16 @@
"This is done by applying in an iterative way a weak (or a standard\n",
"classifier like decision trees) to modify the data. In each iteration\n",
"we emphasize those observations which are misclassified by weighting\n",
-<<<<<<< HEAD
"them with a factor."
]
},
{
"cell_type": "markdown",
- "id": "938ac422",
+ "id": "380dbe84",
"metadata": {
"editable": true
},
"source": [
-=======
- "them with a factor.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## What is boosting? Additive Modelling/Iterative Fitting\n",
"\n",
"Boosting is a way of fitting an additive expansion in a set of\n",
@@ -3250,14 +2573,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "99742488",
+ "id": "be1e7c15",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
@@ -3266,14 +2585,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "29864b76",
+ "id": "fd39aea0",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"where $\\beta_m$ are the expansion parameters to be determined in a\n",
"minimization process and $b(x;\\gamma_m)$ are some simple functions of\n",
@@ -3287,14 +2602,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "55dfbae1",
+ "id": "0f6c751a",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n",
@@ -3303,14 +2614,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "7a5153b5",
+ "id": "4ef3e93e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n",
"$\\gamma_1$ were determined by the Logistic Regression fitting\n",
@@ -3321,14 +2628,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "b5fe05e5",
+ "id": "aeebc227",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
@@ -3337,14 +2640,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "843358e0",
+ "id": "e3a98466",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"In this case the function $f(x)$ was replaced by the design matrix\n",
"$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n",
@@ -3354,14 +2653,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "2b42fc98",
+ "id": "a10e26b1",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
@@ -3370,8 +2665,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "fa243046",
+ "id": "5d4fa044",
"metadata": {
"editable": true
},
@@ -3381,17 +2675,11 @@
},
{
"cell_type": "markdown",
- "id": "668f3417",
+ "id": "3d024e87",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
- "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$.\n",
- "\n",
- "\n",
"## Iterative Fitting, Regression and Squared-error Cost Function\n",
"\n",
"The way we proceed is as follows (here we specialize to the squared-error cost function)\n",
@@ -3408,25 +2696,18 @@
"\n",
"c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n",
"\n",
- "\n",
"We could use any of the algorithms we have discussed till now. If we\n",
"use trees, $\\gamma$ parameterizes the split variables and split points\n",
-<<<<<<< HEAD
"at the internal nodes, and the predictions at the terminal nodes."
]
},
{
"cell_type": "markdown",
- "id": "738db7be",
+ "id": "8cdebebd",
"metadata": {
"editable": true
},
"source": [
-=======
- "at the internal nodes, and the predictions at the terminal nodes.\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Squared-Error Example and Iterative Fitting\n",
"\n",
"To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n",
@@ -3438,14 +2719,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "76855445",
+ "id": "8c3b85c9",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n",
@@ -3454,14 +2731,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d6fc39ce",
+ "id": "da27d4f3",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We start our iteration by simply setting $f_0(x)=0$. \n",
"Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain"
@@ -3469,14 +2742,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f4ab9329",
+ "id": "ca9ce265",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n",
@@ -3485,28 +2754,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "63fdbf59",
+ "id": "2e396660",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"and"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "95ed39a8",
+ "id": "8ab64f17",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n",
@@ -3515,28 +2776,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "9ad3b524",
+ "id": "9ac6b25c",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "a4bb913d",
+ "id": "81f7db3a",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n",
@@ -3545,28 +2798,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "5731b88a",
+ "id": "6050ddb9",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "05cb71a7",
+ "id": "c7b71542",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n",
@@ -3575,36 +2820,25 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "cebf470f",
+ "id": "acb23697",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n",
"for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n",
"\n",
"The solution to these two equations gives us in turn $\\beta_1$ and $\\gamma_1$ leading to the new expression for $f_1(x)$ as\n",
-<<<<<<< HEAD
"$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$."
]
},
{
"cell_type": "markdown",
- "id": "5043858f",
+ "id": "39e88966",
"metadata": {
"editable": true
},
"source": [
-=======
- "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$. \n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Iterative Fitting, Classification and AdaBoost\n",
"\n",
"Let us consider a binary classification problem with two outcomes $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n",
@@ -3616,14 +2850,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "714ea4ee",
+ "id": "ba74cd31",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n",
@@ -3632,14 +2862,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "3f3eafcf",
+ "id": "c55570cc",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"The iterative procedure starts with defining a weak classifier whose\n",
"error rate is barely better than random guessing. The iterative\n",
@@ -3652,14 +2878,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "889882d2",
+ "id": "6ed90583",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
@@ -3668,28 +2890,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "0f1b8941",
+ "id": "fcc3f37d",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"will be a function of"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "a3bb1f79",
+ "id": "d07f3f96",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n",
@@ -3698,14 +2912,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "88df6c57",
+ "id": "11d8a172",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Adaptive Boosting, AdaBoost\n",
"\n",
@@ -3714,14 +2924,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "3c9d9ac3",
+ "id": "f06b988a",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n",
@@ -3730,14 +2936,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f1f95d4a",
+ "id": "73021baf",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n",
"exponential cost/loss function defined as"
@@ -3745,14 +2947,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "43f589be",
+ "id": "8c03b23b",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n",
@@ -3761,14 +2959,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d96eaaee",
+ "id": "34166107",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n",
"This is normally done in two steps. Let us however first rewrite the cost function as"
@@ -3776,14 +2970,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "8b948bbb",
+ "id": "6c0859a1",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n",
@@ -3792,8 +2982,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "3f3cc06e",
+ "id": "9b72d334",
"metadata": {
"editable": true
},
@@ -3803,16 +2992,11 @@
},
{
"cell_type": "markdown",
- "id": "0b1c6031",
+ "id": "cd7d506e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
- "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$.\n",
- "\n",
"## Building up AdaBoost\n",
"\n",
"First, for any $\\beta > 0$, we optimize $G$ by setting"
@@ -3820,14 +3004,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1ade6746",
+ "id": "4f8a648c",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n",
@@ -3836,14 +3016,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "a4bbc019",
+ "id": "cbfc8015",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which is the classifier that minimizes the weighted error rate in predicting $y$.\n",
"\n",
@@ -3852,14 +3028,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "4fd3dea0",
+ "id": "60bc67c2",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n",
@@ -3868,28 +3040,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ca658077",
+ "id": "bc4076c2",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which can be rewritten as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "b9829b00",
+ "id": "c0adb2aa",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n",
@@ -3898,28 +3062,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d744ecab",
+ "id": "c88dbf7a",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which leads to"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "35adfc8e",
+ "id": "335e9e13",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n",
@@ -3928,28 +3084,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1705faa0",
+ "id": "78516dd9",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"where we have redefined the error as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "267b593c",
+ "id": "dd5638b4",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n",
@@ -3958,28 +3106,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "e484405e",
+ "id": "283e7239",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"which leads to an update of"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ffdf57ea",
+ "id": "49876471",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n",
@@ -3988,28 +3128,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d59e62b1",
+ "id": "cb5707ea",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"This leads to the new weights"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "87a66ea2",
+ "id": "64b3a020",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n",
@@ -4018,14 +3150,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "5f13a75a",
+ "id": "0de3a3d8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Adaptive boosting: AdaBoost, Basic Algorithm\n",
"\n",
@@ -4042,14 +3170,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "8a00cea3",
+ "id": "ad43a87d",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n",
@@ -4058,8 +3182,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d9a59dc0",
+ "id": "c6981fd8",
"metadata": {
"editable": true
},
@@ -4069,16 +3192,11 @@
},
{
"cell_type": "markdown",
- "id": "6d602605",
+ "id": "cbfcd3b6",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
- "where the function $I()$ is one if we misclassify and zero if we classify correctly. \n",
- "\n",
"## Basic Steps of AdaBoost\n",
"\n",
"With the above definitions we are now ready to set up the algorithm for AdaBoost.\n",
@@ -4090,14 +3208,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "69942aec",
+ "id": "045795f4",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n",
@@ -4106,14 +3220,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "e9ec97a5",
+ "id": "5aff61cf",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n",
"\n",
@@ -4125,7 +3235,6 @@
"\n",
"d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n",
"\n",
- "\n",
"5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n",
"\n",
"For the iterations with $m \\le 2$ the weights are modified\n",
@@ -4134,23 +3243,16 @@
"classified properly. As this proceeds, the observations which were\n",
"difficult to classifiy correctly are given a larger influence. Each\n",
"new classification step $m$ is then forced to concentrate on those\n",
-<<<<<<< HEAD
"observations that are missed in the previous iterations."
]
},
{
"cell_type": "markdown",
- "id": "de9119e8",
+ "id": "56c77f22",
"metadata": {
"editable": true
},
"source": [
-=======
- "observations that are missed in the previous iterations.\n",
- "\n",
- "\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## AdaBoost Examples\n",
"\n",
"Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here."
@@ -4158,14 +3260,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 36,
- "id": "f790730a",
-=======
"execution_count": 26,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "4db502bc",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -4194,14 +3293,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1d164a72",
+ "id": "bb7788c8",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n",
"\n",
@@ -4211,21 +3306,16 @@
"\n",
"In order to understand the method, let us illustrate its basics by\n",
"bringing back the essential steps in linear regression, where our cost\n",
-<<<<<<< HEAD
"function was the least squares function."
]
},
{
"cell_type": "markdown",
- "id": "2aea58b1",
+ "id": "93e8b283",
"metadata": {
"editable": true
},
"source": [
-=======
- "function was the least squares function.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## The Squared-Error again! Steepest Descent\n",
"\n",
"We start again with our cost function ${\\cal C}(\\boldsymbol{y}m\\boldsymbol{f})=\\sum_{i=0}^{n-1}{\\cal L}(y_i, f(x_i))$ where we want to minimize\n",
@@ -4234,14 +3324,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "9fe0e925",
+ "id": "b42526e9",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
@@ -4250,28 +3336,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "93d443b7",
+ "id": "2cebf557",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ff0a341f",
+ "id": "a007756e",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_M(x) = \\sum_{m=0}^M h_m(x).\n",
@@ -4280,28 +3358,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "7a54de9d",
+ "id": "81f46e4f",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"In the steepest decent approach we approximate $h_m(x) = -\\rho_m g_m(x)$, where $\\rho_m$ is a scalar and $g_m(x)$ the gradient defined as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "f7b3ed21",
+ "id": "fbc9e466",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"g_m(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{m-1}(x_i)}.\n",
@@ -4310,14 +3380,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "d76a3b92",
+ "id": "c44bf568",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"With the new gradient we can update $f_m(x) = f_{m-1}(x) -\\rho_m g_m(x)$. Using the above squared-error function we see that\n",
"the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n",
@@ -4327,14 +3393,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "7ebc7787",
+ "id": "85b7252b",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n",
@@ -4343,14 +3405,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "81f21ab2",
+ "id": "b31361ef",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Steepest Descent Example\n",
"\n",
@@ -4359,14 +3417,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "c3b3e85b",
+ "id": "2942d579",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n",
@@ -4375,28 +3429,20 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "75c9d363",
+ "id": "9bc7c1a0",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"We can then proceed and compute"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "ec040a0c",
+ "id": "047623b6",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"g_2(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,\n",
@@ -4405,8 +3451,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "1c51f8d8",
+ "id": "6f8761e3",
"metadata": {
"editable": true
},
@@ -4416,16 +3461,11 @@
},
{
"cell_type": "markdown",
- "id": "40aa6a3a",
+ "id": "c574cb98",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
- "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**. \n",
- "\n",
"## Gradient Boosting, algorithm\n",
"\n",
"Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,\n",
@@ -4437,14 +3477,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "b90f8570",
+ "id": "1cd0b6a4",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
@@ -4453,14 +3489,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "8b448fbd",
+ "id": "3fb61079",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"The way we proceed in an iterative fashion is to\n",
"1. Initialize our estimate $f_0(x)$.\n",
@@ -4473,35 +3505,26 @@
"\n",
"c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;\n",
"\n",
-<<<<<<< HEAD
"4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$."
]
},
{
"cell_type": "markdown",
- "id": "05caebd1",
+ "id": "78b5941b",
"metadata": {
"editable": true
},
"source": [
-=======
- "\n",
- "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$.\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Gradient Boosting, Examples of Regression"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 37,
- "id": "fa49f235",
-=======
"execution_count": 27,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "8473365f",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -4555,28 +3578,21 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "98586a10",
+ "id": "5c9a2fd6",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Gradient Boosting, Classification Example"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 38,
- "id": "d21bf444",
-=======
"execution_count": 28,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "6a34550c",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -4624,18 +3640,13 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "e0d676e3",
+ "id": "f6443c63",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## XGBoost: Extreme Gradient Boosting\n",
"\n",
- "\n",
"[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n",
"Boosting, is an optimized distributed gradient boosting library\n",
"designed to be highly efficient, flexible and portable. It implements\n",
@@ -4647,34 +3658,26 @@
"boosting system. It has a theoretically justified weighted quantile\n",
"sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.\n",
"\n",
-<<<<<<< HEAD
"It is now the algorithm which wins essentially all ML competitions!!!"
]
},
{
"cell_type": "markdown",
- "id": "71519f2b",
+ "id": "d143a783",
"metadata": {
"editable": true
},
"source": [
-=======
- "It is now the algorithm which wins essentially all ML competitions!!!\n",
- "\n",
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"## Regression Case"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 39,
- "id": "b375c6ca",
-=======
"execution_count": 29,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "d9b2ef60",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -4728,14 +3731,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
- "id": "761ccc1e",
+ "id": "6e28b9fe",
"metadata": {
"editable": true
},
-=======
- "metadata": {},
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
"source": [
"## Xgboost on the Cancer Data\n",
"\n",
@@ -4744,14 +3743,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 40,
- "id": "0673208c",
-=======
"execution_count": 30,
->>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
+ "id": "c70a1cfb",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
@@ -4812,5 +3808,5 @@
],
"metadata": {},
"nbformat": 4,
- "nbformat_minor": 4
+ "nbformat_minor": 5
}
diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt
index 8cc5502a5..957a2d935 100644
--- a/doc/src/week45/week45.do.txt
+++ b/doc/src/week45/week45.do.txt
@@ -440,7 +440,7 @@ s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
!split
-===== Gini Index?Coefficient/Impurity =====
+===== Gini Index (or Coefficient or Impurity) =====
The Gini index $g$ gives us the degree of probability of a specific
variable that is wrongly classified.
@@ -453,7 +453,7 @@ o A value $g=0.5$ means that the elements in a node are uniformly distributed a
It favors binary splitting.
!split
-===== Why binary split? =====
+===== Why binary splits? =====
It is custom to split to a tree uising binary splits. The reason is
that multiway splits fragment the data too quickly, leaving
@@ -461,6 +461,61 @@ insufficient data at the next level down. Multiway splits can be
achieved by a series of binary split and this is normally preferred.
+!split
+===== Computing a Tree using the Gini Index =====
+
+Consider the following example with attributes/features and two
+possible outcomes (classes) for each attribute. Assume we wish to find some
+correlations between the average grade of a student as function of the
+number of hours studied and hours slept. We want also to correlate the
+grade in a given course with the general trend, whether the students
+recently has gotten grades below average or above.
+
+We have three features/attributes
+o Trend of average grades before present course, classified as either below or above the average grade of the whole class
+o The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one $ECTS$ which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.
+o The number of hours slept as high for more than $8$ hours and below for less than 8 hours of sleep, classified again as either high or low
+o The final grade whether it is above or below average
+
+
+!split
+===== The Table =====
+
+|---------------------------------------------------|
+| Grade Trend | Hours slept | Hours Studied | Grade |
+|---------------------------------------------------|
+
+
+
+!split
+===== Computing the various Gini Indices =====
+
+In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+
+!bblock Gini index for Average trend
+
+!eblock
+
+
+!split
+===== Computing the various Gini Indices, Hours slept =====
+
+
+!bblock Gini index for hour slept
+
+!eblock
+
+
+!split
+===== Computing the various Gini Indices, Hours studied =====
+
+
+!bblock Gini index for hour studied
+
+!eblock
+
+
!split