diff --git a/doc/pub/week47/html/._week47-bs000.html b/doc/pub/week47/html/._week47-bs000.html index 8424394b5..7f570d170 100644 --- a/doc/pub/week47/html/._week47-bs000.html +++ b/doc/pub/week47/html/._week47-bs000.html @@ -37,6 +37,116 @@ doconce format html week47.do.txt --html_style=bootstrap --pygments_html_style=d
@@ -144,29 +262,70 @@ MathJax.Hub.Config({ Contents @@ -221,7 +380,7 @@ MathJax.Hub.Config({
-
Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. -
- -As in bagging, we build a -number of decision trees on bootstrapped training samples. But when -building these decision trees, each time a split in a tree is -considered, a random sample of \( m \) predictors is chosen as split -candidates from the full set of \( p \) predictors. The split is allowed to -use only one of those \( m \) predictors. -
- -A fresh sample of \( m \) predictors is -taken at each split, and typically we choose +
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
$$ -m\approx \sqrt{p}. +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, $$ -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. +
where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \).
@@ -236,7 +377,7 @@ this setting.
-
The algorithm described here can be applied to both classification and regression problems.
+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 +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. +
-We will grow of forest of say \( B \) trees.
-diff --git a/doc/pub/week47/html/._week47-bs004.html b/doc/pub/week47/html/._week47-bs004.html index 0cdcd791e..c0de946b2 100644 --- a/doc/pub/week47/html/._week47-bs004.html +++ b/doc/pub/week47/html/._week47-bs004.html @@ -37,6 +37,116 @@ doconce format html week47.do.txt --html_style=bootstrap --pygments_html_style=d @@ -144,29 +262,70 @@ MathJax.Hub.Config({ Contents @@ -178,98 +337,52 @@ MathJax.Hub.Config({
-
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
+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\},
+$$
-# Load the data
-cancer = load_breast_cancer()
+and
+$$
+\left\{X\vert x_j \geq s\right\},
+$$
-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)
-#define methods
-# Logistic Regression
-logreg = LogisticRegression(solver='lbfgs')
-# Support vector machine
-svm = SVC(gamma='auto', C=100)
-# Decision Trees
-deep_tree_clf = DecisionTreeClassifier(max_depth=None)
-#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)))
+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,
+$$
-
-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. +
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.
-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. +
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 +done quite quickly, especially when the number of features \( p \) is not +too large. +
+ +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 +space, we split one of the two previously identified regions. We now +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.
@@ -291,7 +404,7 @@ discrimination threshold is varied. It plots the true positive rate against the
- -
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)
-
-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 +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.
@@ -251,7 +375,7 @@ np.sum(y_pred =
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.
+ For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that 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.
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.
+ 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.
+ 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 \).
@@ -213,7 +388,7 @@ them with a factor.
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
- 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
- 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 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 \).
@@ -247,7 +380,7 @@ $$
The way we proceed is as follows (here we specialize to the squared-error cost function) 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.
+ 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
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+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.
@@ -220,7 +376,7 @@ at the internal nodes, and the predictions at the terminal nodes.
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 We start our iteration by simply setting \( f_0(x)=0 \).
-Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
- and We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have 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 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
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+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.
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 \).
+ 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.
@@ -244,7 +382,7 @@ for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equa
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\} \).
+ 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.
The error rate of the training sample is then 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) \).
+ 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
Here we will express our function \( f(x) \) in terms of \( G(x) \). That is will be a function of 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
+ In our iterative procedure we define thus 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
- 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
- where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
@@ -227,7 +419,7 @@ $$
First, for any \( \beta > 0 \), we optimize \( G \) by setting which is the classifier that minimizes the weighted error rate in predicting \( y \). We can do this by rewriting which can be rewritten as which leads to where we have redefined the error as which leads to an update of This leads to the new weights
@@ -243,7 +410,7 @@ $$
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} \).
- Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. We have already defined the misclassification error \( \mathrm{err} \) as where the function \( I() \) is one if we misclassify and zero if we classify correctly.
@@ -221,7 +396,7 @@ $$
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.
+ 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:
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.
-
@@ -235,7 +399,7 @@ observations that are missed in the previous iterations.
Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. 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.
+
@@ -243,6 +374,8 @@ plt.show()
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.
+ 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.
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.
+ 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
+ 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 \).
@@ -213,6 +385,9 @@ function was the least squares function.
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 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
We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as Here the MSE for a specific node is 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 with 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)) \).
+ 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.
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
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that We can then proceed and compute 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. It is custom to split to a tree uising binary splits. The reason is
+that multiway splits fragment the data too quickly, leaving
+insufficient data at the next level down. Multiway splits can be
+achieved by a series of binary split and this is normally preferred.
+
@@ -213,6 +366,11 @@ $$
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.
+ 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.
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 The way we proceed in an iterative fashion is to We have three features/attributes
@@ -221,6 +374,12 @@ $$
@@ -262,6 +380,13 @@ plt.show()
In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+ See whiteboard notes from lecture November 11 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf 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!!!
@@ -212,6 +439,15 @@ sketch for efficient proposal calculation. It introduces a novel sparsity-aware
The next 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
@@ -260,6 +394,16 @@ plt.show()
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. 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.
@@ -402,7 +455,7 @@ MathJax.Hub.Config({
@@ -407,7 +415,7 @@ MathJax.Hub.Config({
Artificial intelligence is built upon integrated machine learning
-algorithms as discussed in this course, which in turn are fundamentally rooted in optimization and
-statistical learning.
- Can we have Artificial Intelligence without Machine Learning? See this post for inspiration.
@@ -409,7 +471,7 @@ statistical learning.
Traditionally the field of machine learning has had its main focus on
-predictions and correlations. These concepts outline in some sense
-the difference between machine learning and what is normally called
-Bayesian statistics or Bayesian inference.
- In machine learning and prediction based tasks, we are often
-interested in developing algorithms that are capable of learning
-patterns from given data in an automated fashion, and then using these
-learned patterns to make predictions or assessments of newly given
-data. In many cases, our primary concern is the quality of the
-predictions or assessments, and we are less concerned with the
-underlying patterns that were learned in order to make these
-predictions. This leads to what normally has been labeled as a
-frequentist approach.
-
You should keep in mind that the division between a traditional
-frequentist approach with focus on predictions and correlations only
-and a Bayesian approach with an emphasis on estimations and
-causations, is not that sharp. Machine learning can be frequentist
-with ensemble methods (EMB) as examples and Bayesian with Gaussian
-Processes as examples.
- If one views ML from a statistical learning
-perspective, one is then equally interested in estimating errors as
-one is in finding correlations and making predictions. It is important
-to keep in mind that the frequentist and Bayesian approaches differ
-mainly in their interpretations of probability. In the frequentist
-world, we can only assign probabilities to repeated random
-phenomena. From the observations of these phenomena, we can infer the
-probability of occurrence of a specific event. In Bayesian
-statistics, we assign probabilities to specific events and the
-probability represents the measure of belief/confidence for that
-event. The belief can be updated in the light of new evidence.
+ However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
@@ -423,7 +378,7 @@ event. The belief can be updated in the light of new evidence.
The course has two central parts As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+ This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+ We discuss these methods here.
The following topics have been discussed:
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. The following topics will be covered
The course introduces a variety of central algorithms and methods
-essential for studies of data analysis and machine learning. The
-course is project based and through the various projects, normally
-three, you will be exposed to fundamental research problems
-in these fields, with the aim to reproduce state of the art scientific
-results. The students will learn to develop and structure large codes
-for studying these systems, get acquainted with computing facilities
-and learn to handle large scientific projects. A good scientific and
-ethical conduct is emphasized throughout the course.
+ 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.
Huge amounts of data sets require automation, classical analysis tools often inadequate.
-High energy physics hit this wall in the 90’s.
-In 2009 single top quark production was determined via Boosted decision trees, Bayesian
-Neural Networks, etc.. Similarly, the search for Higgs was a statistical learning tour de force. See this link on Kaggle.com.
-
@@ -414,7 +424,7 @@ Neural Networks, etc.. Similarly, the search for Higgs was a statistical lea
Where to find recent results:
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.
Whitening is a decorrelation transformation that transforms a set of
-random variables into a set of new random variables with identity
-covariance (uncorrelated with unit variances).
+ 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.
@@ -424,7 +378,7 @@ covariance (uncorrelated with unit variances).
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.
+
Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft
-classifiers, depths of trees and many other. Need to explore a large
-set of hyperparameters and regularization methods.
+ 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 \)).
When do we resample? Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+ As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
+ A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
+ 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.
+
The algorithm described here can be applied to both classification and regression problems. We will grow of forest of say \( B \) trees.
@@ -413,7 +379,7 @@ MathJax.Hub.Config({
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.
+
Based on multi-layer nonlinear neural networks, deep learning can
-learn directly from raw data, automatically extract and abstract
-features from layer to layer, and then achieve the goal of regression,
-classification, or ranking. Deep learning has made breakthroughs in
-computer vision, speech processing and natural language, and reached
-or even surpassed human level. The success of deep learning is mainly
-due to the three factors: big data, big model, and big computing.
- In the past few decades, many different architectures of deep neural
-networks have been proposed, such as
-
The approaches to machine learning are many, but are often split into two main categories.
-In supervised learning we know the answer to a problem,
-and let the computer deduce the logic behind it. On the other hand, unsupervised learning
-is a method for finding patterns and relationship in data sets without any prior knowledge of the system.
-Some authours also operate with a third category, namely reinforcement learning. This is a paradigm
-of learning inspired by behavioural psychology, where learning is achieved by trial-and-error,
-solely from rewards and punishment.
+ 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.
Another way to categorize machine learning tasks is to consider the desired output of a system.
-Some of the most common tasks are:
+ 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 known as restricted Boltzmann Machines (RMB) have received a lot of attention lately.
-One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics.
+ 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
+ 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 original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. 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
+ Furthermore, they have been used to solve complicated quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models. 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 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 \).
@@ -410,7 +409,7 @@ One of the major reasons is that they can be stacked layer-wise to build deep ne
Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? Simplest approach to generative deep learning. The way we proceed is as follows (here we specialize to the squared-error cost function) 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.
+
History: The RBM was developed by amongst others Geoffrey Hinton, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google. 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 We start our iteration by simply setting \( f_0(x)=0 \).
+Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
+ and We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have 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 \).
+
@@ -409,7 +404,7 @@ MathJax.Hub.Config({
A BM is what we would call an undirected probabilistic graphical model
-with stochastic continuous or discrete units.
+ 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\} \).
It is interpreted as a stochastic recurrent neural network where the
-state of each unit(neurons/nodes) depends on the units it is connected
-to. The weights in the network represent thus the strength of the
-interaction between various units/nodes.
- The error rate of the training sample is then It turns into a Hopfield network if we choose deterministic rather
-than stochastic units. In contrast to a Hopfield network, a BM is a
-so-called generative model. It allows us to generate new samples from
-the learned distribution.
+$$
+\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) \).
Here we will express our function \( f(x) \) in terms of \( G(x) \). That is will be a function of
@@ -434,7 +393,7 @@ the learned distribution.
A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \). In our iterative procedure we define thus Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \). BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS.
-Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below.
+ 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
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
+ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
@@ -430,7 +386,7 @@ Here we take away all lateral connections between nodes in the visible layer as
First, for any \( \beta > 0 \), we optimize \( G \) by setting which is the classifier that minimizes the weighted error rate in predicting \( y \). We can do this by rewriting which can be rewritten as which leads to where we have redefined the error as which leads to an update of This leads to the new weights
@@ -408,7 +402,7 @@ MathJax.Hub.Config({
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 where the function \( I() \) is one if we misclassify and zero if we classify correctly.
The goal of the hidden layer is to increase the model's expressive
-power. We encode complex interactions between visible variables by
-introducing additional, hidden variables that interact with visible
-degrees of freedom in a simple manner, yet still reproduce the complex
-correlations between visible degrees in the data once marginalized
-over (integrated out).
+ 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.
The restricted Boltzmann machine is described by a Boltzmann distribution Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. where \( Z \) is the normalization constant or partition function, defined as It is common to ignore \( T_0 \) by setting it to one.
@@ -420,7 +403,7 @@ $$
The function \( E(\mathbf{x},\mathbf{h}) \) gives the energy of a
-configuration (pair of vectors) \( (\mathbf{x}, \mathbf{h}) \). The lower
-the energy of a configuration, the higher the probability of it. This
-function also depends on the parameters \( \mathbf{a} \), \( \mathbf{b} \) and
-\( W \). Thus, when we adjust them during the learning procedure, we are
-adjusting the energy function to best fit our problem.
- An expression for the energy function is Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. Note that there is no connection between nodes in a layer. The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively. The connection between the nodes in the two layers is given by the weights \( w_{ij} \).
@@ -421,7 +465,7 @@ $$
There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \). RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows: where the binary values taken on by the nodes are most commonly 0 and 1. Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary: Gradient boosting is again a similar technique to Adaptive boosting,
+it combines so-called weak classifiers or regressors into a strong
+method via a series of iterations.
+ In order to understand the method, let us illustrate its basics by
+bringing back the essential steps in linear regression, where our cost
+function was the least squares function.
+
@@ -433,8 +373,6 @@ $$
Other types of units include: To read more, see Lectures on Boltzmann machines in Physics. 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
+ We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) 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 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
@@ -412,9 +390,6 @@ MathJax.Hub.Config({
Autoencoders are artificial neural networks capable of learning
-efficient representations of the input data (these representations are called codings) without
-any supervision (i.e., the training set is unlabeled). These codings
-typically have a much lower dimensionality than the input data, making
-autoencoders useful for dimensionality reduction.
- Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that More importantly, autoencoders act as powerful feature detectors, and
-they can be used for unsupervised pretraining of deep neural networks.
- We can then proceed and compute Lastly, they are capable of randomly generating new data that looks
-very similar to the training data; this is called a generative
-model. For example, you could train an autoencoder on pictures of
-faces, and it would then be able to generate new faces. Surprisingly,
-autoencoders work by simply learning to copy their inputs to their
-outputs. This may sound like a trivial task, but we will see that
-constraining the network in various ways can make it rather
-difficult. For example, you can limit the size of the internal
-representation, or you can add noise to the inputs and train the
-network to recover the original inputs. These constraints prevent the
-autoencoder from trivially copying the inputs directly to the outputs,
-which forces it to learn efficient ways of representing the data. In
-short, the codings are byproducts of the autoencoder’s attempt to
-learn the identity function under some constraints.
- See also A. Geron's textbook, chapter 15. 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.
@@ -430,10 +373,6 @@ learn the identity function under some constraints.
This is an important topic if we aim at extracting a probability
-distribution. This gives us also a confidence interval and error
-estimates.
+ 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.
Bayesian machine learning allows us to encode our prior beliefs about
-what those models should look like, independent of what the data tells
-us. This is especially useful when we don’t have a ton of data to
-confidently learn our model.
- See also the slides here. 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 The way we proceed in an iterative fashion is to
Reinforcement Learning (RL) is one of the most exciting fields of
-Machine Learning today, and also one of the oldest. It has been around
-since the 1950s, producing many interesting applications over the
-years.
- It studies
-how agents take actions based on trial and error, so as to maximize
-some notion of cumulative reward in a dynamic system or
-environment. Due to its generality, the problem has also been studied
-in many other disciplines, such as game theory, control theory,
-operations research, information theory, multi-agent systems, swarm
-intelligence, statistics, and genetic algorithms.
- In March 2016, AlphaGo, a computer program that plays the board game
-Go, beat Lee Sedol in a five-game match. This was the first time a
-computer Go program had beaten a 9-dan (highest rank) professional
-without handicaps. AlphaGo is based on deep convolutional neural
-networks and reinforcement learning. AlphaGo’s victory was a major
-milestone in artificial intelligence and it has also made
-reinforcement learning a hot research area in the field of machine
-learning.
- Lecture on Reinforcement Learning. See also A. Geron's textbook, chapter 16.
@@ -426,12 +422,6 @@ learning.
The goal of transfer learning is to transfer the model or knowledge
-obtained from a source task to the target task, in order to resolve
-the issues of insufficient training data in the target task. The
-rationality of doing so lies in that usually the source and target
-tasks have inter-correlations, and therefore either the features,
-samples, or models in the source task might provide useful information
-for us to better solve the target task. Transfer learning is a hot
-research topic in recent years, with many problems still waiting to be studied.
-
@@ -408,13 +420,6 @@ research topic in recent years, with many problems still waiting to be studied.
The conventional deep generative model has a potential problem: the
-model tends to generate extreme instances to maximize the
-probabilistic likelihood, which will hurt its performance. Adversarial
-learning utilizes the adversarial behaviors (e.g., generating
-adversarial instances or training an adversarial model) to enhance the
-robustness of the model and improve the quality of the generated
-data. In recent years, one of the most promising unsupervised learning
-technologies, generative adversarial networks (GAN), has already been
-successfully applied to image, speech, and text.
+ 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.
Lecture on adversial learning. 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!!!
@@ -408,14 +372,6 @@ successfully applied to image, speech, and text.
Dual learning is a new learning paradigm, the basic idea of which is
-to use the primal-dual structure between machine learning tasks to
-obtain effective feedback/regularization, and guide and strengthen the
-learning process, thus reducing the requirement of large-scale labeled
-data for deep learning. The idea of dual learning has been applied to
-many problems in machine learning, including machine translation,
-image style conversion, question answering and generation, image
-classification and generation, text classification and generation,
-image-to-text, and text-to-image.
-
@@ -405,15 +420,6 @@ image-to-text, and text-to-image.
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. Distributed computation will speed up machine learning algorithms,
-significantly improve their efficiency, and thus enlarge their
-application. When distributed meets machine learning, more than just
-implementing the machine learning algorithms in parallel is required.
-
@@ -399,16 +430,6 @@ implementing the machine learning algorithms in parallel is required.
Meta learning is an emerging research direction in machine
-learning. Roughly speaking, meta learning concerns learning how to
-learn, and focuses on the understanding and adaptation of the learning
-itself, instead of just completing a specific learning task. That is,
-a meta learner needs to be able to evaluate its own learning methods
-and adjust its own learning methods according to specific learning
-tasks.
-
@@ -401,18 +452,6 @@ tasks.
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
+ where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+ 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
+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
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+ and so that we obtain the lowest MSE, that is 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
+\( \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
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+ 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
+space, we split one of the two previously identified regions. We now
+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
+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
+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. For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that 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
+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.
+ 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 \).
+
+
+
+ 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
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+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.
+ 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
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+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.
+ 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.
+ 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
+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
+ 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
+
+
+
+ Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. 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:
+ 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 \).
+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
+ 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 \).
+ 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
+ Here the MSE for a specific node is defined as with 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.
+ It is custom to split to a tree uising binary splits. The reason is
+that multiway splits fragment the data too quickly, leaving
+insufficient data at the next level down. Multiway splits can be
+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 In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+
+ See whiteboard notes from lecture November 11 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf The next 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 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.
+ However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+ As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+ This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+
+ We discuss these methods here. 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. 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.
+ 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. 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.
+ 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.
+ 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 \)).
+
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
+ where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+ 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
+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
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+ and so that we obtain the lowest MSE, that is 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
+\( \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
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+ 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
+space, we split one of the two previously identified regions. We now
+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
+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
+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. For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that 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
+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.
+ 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 \).
+
+
+ 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
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+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.
+ 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
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+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.
+ 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.
+ 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
+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
+ 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
+ Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. 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:
+ 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 \).
+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
+ 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 \).
+ 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
+ Here the MSE for a specific node is defined as with 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.
+ It is custom to split to a tree uising binary splits. The reason is
+that multiway splits fragment the data too quickly, leaving
+insufficient data at the next level down. Multiway splits can be
+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 In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+
+ See whiteboard notes from lecture November 11 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf The next 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 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. However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+ As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+ This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+ We discuss these methods here. 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. 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.
+ 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. 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.
+ 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.
+ 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 \)).
+
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
+ where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+ 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
+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
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+ and so that we obtain the lowest MSE, that is 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
+\( \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
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+ 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
+space, we split one of the two previously identified regions. We now
+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
+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
+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. For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that 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
+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.
+ 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 \).
+
+
+ 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
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+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.
+ 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
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+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.
+ 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.
+ 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
+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
+ 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
+ Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. 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:
+ 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 \).
+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
+ 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 \).
+ 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
+ Here the MSE for a specific node is defined as with 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.
+ It is custom to split to a tree uising binary splits. The reason is
+that multiway splits fragment the data too quickly, leaving
+insufficient data at the next level down. Multiway splits can be
+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 In computations we will translate all classes into numbers. Being
+these binary classes, they can easily be split into ones and zeros.
+
+ See whiteboard notes from lecture November 11 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf The next 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 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. However, by aggregating many decision trees, using methods like
+bagging, random forests, and boosting, the predictive performance of
+trees can be substantially improved.
+ As stated above and seen in many of the examples discussed here about
+a single decision tree, we often end up overfitting our training
+data. This normally means that we have a high variance. Can we reduce
+the variance of a statistical learning method?
+ This leads us to a set of different methods that can combine different
+machine learning algorithms or just use one of them to construct
+forests and jungles of trees, homogeneous ones or heterogenous
+ones. These methods are recognized by different names which we will
+try to explain here. These are
+ We discuss these methods here. 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. 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.
+ 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. 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.
+ 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.
+ 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 \)).
+ Figure 1: Boosting, a Bird's Eye View
+Cost complexity pruning
-What is boosting? Additive Modelling/Iterative Fitting
+Schematic Regression Procedure
-
+
+
+
+Iterative Fitting, Regression and Squared-error Cost Function
+A Classification Tree
-
-
-
-Squared-Error Example and Iterative Fitting
+Growing a classification tree
-Iterative Fitting, Classification and AdaBoost
+Classification tree, how to split nodes
-
+
$$
-G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
+$$
+
+
+
+$$
+g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
+$$
+
+
+
+$$
+s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
$$
@@ -234,7 +405,7 @@ $$
Adaptive Boosting, AdaBoost
+Visualizing the Tree, Classification
-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
-
+Building up AdaBoost
+Visualizing the Tree, The Moons
-# 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
-
+Adaptive boosting: AdaBoost, Basic Algorithm
+Other ways of visualizing the trees
-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)
+
+Basic Steps of AdaBoost
+Printing out as text
-
-
-$$
-\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},
-$$
-
-
-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)
+
+AdaBoost Examples
-
-from sklearn.ensemble import AdaBoostClassifier
-
-ada_clf = AdaBoostClassifier(
- DecisionTreeClassifier(max_depth=2), n_estimators=200,
- algorithm="SAMME.R", learning_rate=0.01, random_state=42)
-ada_clf.fit(X_train, y_train)
-y_pred = ada_clf.predict(X_test)
-skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
-plt.show()
-y_probas = ada_clf.predict_proba(X_test)
-skplt.metrics.plot_roc(y_test, y_probas)
-plt.show()
-skplt.metrics.plot_cumulative_gain(y_test, y_probas)
-plt.show()
-
-Algorithms for Setting up Decision Trees
+
+
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
+The CART algorithm for Classification
-The Squared-Error again! Steepest Descent
+The CART algorithm for Regression
-Steepest Descent Example
+Why binary splits?
-Gradient Boosting, algorithm
+Computing a Tree using the Gini Index
-
-
-Gradient Boosting, Examples of Regression
-
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import train_test_split
-from sklearn.ensemble import GradientBoostingRegressor
-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)
-
-for degree in range(1,maxdegree):
- model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
- model.fit(X_train,y_train)
- y_pred = model.predict(X_test)
- 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()
-
-The Table
+
+
+
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+ Above Low High Above
+ Below High Low Below
+ Above Low High Above
+ Above High High Above
+ Below Low High Below
+ Above Low Low Below
+ Below High High Below
+ Below Low High Below
+ Above Low Low Below
+
+ Above High High Above Gradient Boosting, Classification Example
+Computing the various Gini Indices
-
-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
+
+XGBoost: Extreme Gradient Boosting
+A possible code using Scikit-Learn
-# 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
+
+# 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("grades.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+grades = pd.read_csv(infile)
+grades = pd.DataFrame(grades)
+display(grades)
+# Features and targets
+X = grades.loc[:, grades.columns != 'Grade'].values
+y = grades.loc[:, grades.columns == 'Grade'].values
+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/grade.dot",
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
+os.system(cmd)
+
+Regression Case
+Further example: Computing the Gini index
+import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import train_test_split
-import xgboost as xgb
-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)
-
-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,y_train)
- y_pred = model.predict(X_test)
- 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()
-
-
+
+
+
+
+
+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 Xgboost on the Cancer Data
+Simple Python Code to read in Data and perform Classification
-import matplotlib.pyplot as plt
+
# Common imports
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()
+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
-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)
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-xg_clf = xgb.XGBClassifier()
-xg_clf.fit(X_train_scaled,y_train)
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-y_test = xg_clf.predict(X_test_scaled)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-print("Test set accuracy with Gradient Boosting and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-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()
+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)
-xgb.plot_tree(xg_clf,num_trees=0)
-plt.rcParams['figure.figsize'] = [50, 10]
-save_fig("xgtree")
-plt.show()
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-xgb.plot_importance(xg_clf)
-plt.rcParams['figure.figsize'] = [5, 5]
-save_fig("xgparams")
-plt.show()
+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)
Summary of course
+Computing the Gini Factor
+
+# 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
+
+# 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']))
+
+What? Me worry? No final exam in this course!
-
-
+Regression trees
+
+
+# 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)
+
+What is the link between Artificial Intelligence and Machine Learning and some general Remarks
+Final regressor code
-from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+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()
+
+Going back to the beginning of the semester
-
-Pros and cons of trees, pros
+
+
Not so sharp distinctions
+Disadvantages
-
+
+Topics we have covered this year
+Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
-
-
+Statistical analysis and optimization of data
+An Overview of Ensemble Methods
+
+
+
-
-
Machine learning
+Why Voting?
+
+
-
-Learning outcomes and overarching aims of this course
+Tossing coins
-
-
Perspective on Machine Learning
+Standard imports first
+
+
+
+# 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)
+
+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')
+
+
-
-Machine Learning Research
+Simple Voting Example, head or tail
+
+
+# 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()
+
+
-
Starting your Machine Learning Project
+Using the Voting Classifier
+
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
-
Choose a Model and Algorithm
+Voting and Bagging
+
+
+
+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))
+
+
-
Preparing Your Data
+Bagging
-
-
-
-
-
-
-
-
-Which Activation and Weights to Choose in Neural Networks
+More bagging
+
+
-
-
-
-
-Optimization Methods and Hyperparameters
-
-
-
-
-
-Making your own Bootstrap: Changing the Level of the Decision Tree
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
+print("Simple tree:",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()
+
+Resampling
+Random forests
-
-
Other courses on Data science and Machine Learning at UiO
+Random Forest Algorithm
+
-
+
+
+
+Additional courses of interest
+Random Forests Compared with other Methods on the Cancer Data
+
+
+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)
+#define methods
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+#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()
+
+What's the future like?
+Compare Bagging on Trees with Random Forests
+
+
+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)
+
+
-
Types of Machine Learning, a repetition
+Boosting, a Bird's Eye View
-
-
-Why Boltzmann machines?
+What is boosting? Additive Modelling/Iterative Fitting
-Boltzmann Machines
+Iterative Fitting, Regression and Squared-error Cost Function
-
-
+
+
+
-Some similarities and differences from DNNs
+Squared-Error Example and Iterative Fitting
-
-
-Boltzmann machines (BM)
+Iterative Fitting, Classification and AdaBoost
-A standard BM setup
+Adaptive Boosting, AdaBoost
-The structure of the RBM network
+Building up AdaBoost
+
+
-
The network
+Adaptive boosting: AdaBoost, Basic Algorithm
+
+
-
Goals
+Basic Steps of AdaBoost
-
+
+$$
+\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},
+$$
+
+
+
+
-
Joint distribution
+AdaBoost Examples
-from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+ DecisionTreeClassifier(max_depth=2), n_estimators=200,
+ algorithm="SAMME.R", learning_rate=0.01, random_state=42)
+ada_clf.fit(X_train, y_train)
+y_pred = ada_clf.predict(X_test)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+Network Elements, the energy function
+Making an ADAboost code yourself
-import numpy as np
-
+Defining different types of RBMs
-Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-More about RBMs
-
-
-
-
-The Squared-Error again! Steepest Descent
+
+Autoencoders: Overarching view
+Steepest Descent Example
-Bayesian Machine Learning
+Gradient Boosting, algorithm
-
+
+Reinforcement Learning
+Gradient Boosting, Examples of Regression
-import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
-
+Transfer learning
+Gradient Boosting, Classification Example
-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 Gradient boosting 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()
+
+Adversarial learning
+XGBoost: Extreme Gradient Boosting
-Dual learning
+Regression Case
+
+
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+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)
+
+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,y_train)
+ y_pred = model.predict(X_test)
+ 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()
+
+Distributed machine learning
+Xgboost on the Cancer Data
+
+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 Gradient Boosting 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()
+
+Meta learning
+Gradient boosting, making our own code for a regression case
-import numpy as np
+class DecisionTreeRegressor:
+ def __init__(self, max_depth=3):
+ self.max_depth = max_depth
+ self.tree = None
+ def fit(self, X, y):
+ self.tree = self._grow_tree(X, y)
+ def _grow_tree(self, X, y, depth=0):
+ n_samples, n_features = X.shape
+ if depth < self.max_depth:
+ best_feature, best_threshold = self._best_split(X, y)
+ if best_feature is not None:
+ left_indices = X[:, best_feature] < best_threshold
+ right_indices = X[:, best_feature] >= best_threshold
+ left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
+ right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
+ return (best_feature, best_threshold, left_child, right_child)
+ return np.mean(y)
+ def _best_split(self, X, y):
+ best_mse = float('inf')
+ best_feature, best_threshold = None, None
+ n_samples, n_features = X.shape
+
+ for feature in range(n_features):
+ thresholds = np.unique(X[:, feature])
+ for threshold in thresholds:
+ left_indices = X[:, feature] < threshold
+ right_indices = X[:, feature] >= threshold
+ if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
+ left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
+ right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
+ mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
+
+ if mse < best_mse:
+ best_mse = mse
+ best_feature = feature
+ best_threshold = threshold
+ return best_feature, best_threshold
+ def predict(self, X):
+ return np.array([self._predict_sample(sample, self.tree) for sample in X])
+ def _predict_sample(self, sample, node):
+ if isinstance(node, tuple):
+ feature, threshold, left_child, right_child = node
+ if sample[feature] < threshold:
+ return self._predict_sample(sample, left_child)
+ else:
+ return self._predict_sample(sample, right_child)
+ return node
+class GradientBoostingRegressor:
+ def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
+ self.n_estimators = n_estimators
+ self.learning_rate = learning_rate
+ self.max_depth = max_depth
+ self.models = []
+ def fit(self, X, y):
+ y_pred = np.zeros(y.shape)
+ for _ in range(self.n_estimators):
+ residuals = y - y_pred
+ model = DecisionTreeRegressor(max_depth=self.max_depth)
+ model.fit(X, residuals)
+ y_pred += self.learning_rate * model.predict(X)
+ self.models.append(model)
+ def predict(self, X):
+ y_pred = np.zeros(X.shape[0])
+ for model in self.models:
+ y_pred += self.learning_rate * model.predict(X)
+ return y_pred
+# Example usage
+if __name__ == "__main__":
+ # Sample data
+ X = np.array([[1], [2], [3], [4], [5]])
+ y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
+ model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
+ model.fit(X, y)
+ predictions = model.predict(X)
+ print("Predictions:", predictions)
+
+
+
-
-
Building a tree, regression
+
+
+
+
+$$
+\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
+$$
+
+
+A top-down approach, recursive binary splitting
+
+Making a tree
+
+
+$$
+\left\{X\vert x_j < s\right\},
+$$
+
+
+
+$$
+\left\{X\vert x_j \geq s\right\},
+$$
+
+
+
+$$
+\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,
+$$
+
+
+Pruning the tree
+
+Cost complexity pruning
+
+
+$$
+\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
+$$
+
+
+Schematic Regression Procedure
+
+
+
+
+
A Classification Tree
+
+Growing a classification tree
+
+Classification tree, how to split nodes
+
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
+$$
+
+
+
+
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
+$$
+
+
+
+
+
+$$
+g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
+$$
+
+
+
+
+
+$$
+s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
+$$
+
+Visualizing the Tree, Classification
+
+
+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)
+
+Visualizing the Tree, The Moons
+
+
+# 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)
+
+Other ways of visualizing the trees
+
+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
+
+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)
+
+Algorithms for Setting up Decision Trees
+
+
+
+The CART algorithm for Classification
+
+
+$$
+C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
+$$
+
+
+The CART algorithm for Regression
+
+
+$$
+C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
+$$
+
+
+
+$$
+\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
+$$
+
+
+
+$$
+\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
+$$
+
+
+Why binary splits?
+
+Computing a Tree using the Gini Index
+
+
+
+The Table
+
+
+
+
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+ Above Low High Above
+ Below High Low Below
+ Above Low High Above
+ Above High High Above
+ Below Low High Below
+ Above Low Low Below
+ Below High High Below
+ Below Low High Below
+ Above Low Low Below
+
+ Above High High Above Computing the various Gini Indices
+
+A possible code using Scikit-Learn
+
+
+
+# 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
+
+# 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("grades.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+grades = pd.read_csv(infile)
+grades = pd.DataFrame(grades)
+display(grades)
+# Features and targets
+X = grades.loc[:, grades.columns != 'Grade'].values
+y = grades.loc[:, grades.columns == 'Grade'].values
+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/grade.dot",
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
+os.system(cmd)
+
+Further example: Computing the Gini index
+
+
+
+
+
+
+
+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 Simple Python Code to read in Data and perform Classification
+
+
+
+# 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
+
+# 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)
+
+Computing the Gini Factor
+
+# 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
+
+# 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']))
+
+Regression trees
+
+
+# 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)
+
+Final regressor code
+
+
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+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()
+
+Pros and cons of trees, pros
+
+
+
+Disadvantages
+
+
+
+Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
+
+
+
+An Overview of Ensemble Methods
+
+
+
+Why Voting?
+
+Tossing coins
+
+Standard imports first
+
+
+
+# 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)
+
+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')
+
+Simple Voting Example, head or tail
+
+
+# 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()
+
+Using the Voting Classifier
+
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+Voting and Bagging
+
+
+
+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))
+
+Bagging
+
+More bagging
+
+Making your own Bootstrap: Changing the Level of the Decision Tree
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
+print("Simple tree:",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()
+
+Random forests
@@ -836,6 +2462,110 @@ plt.show()
Making an ADAboost code yourself
+
+
+
+import numpy as np
+
+class DecisionStump:
+ def fit(self, X, y, weights):
+ m, n = X.shape
+ self.alpha = 0
+ self.threshold = None
+ self.polarity = 1
+
+ min_error = float('inf')
+
+ for feature in range(n):
+ feature_values = np.unique(X[:, feature])
+
+ for threshold in feature_values:
+ for polarity in [1, -1]:
+ predictions = np.ones(m)
+ predictions[X[:, feature] < threshold] = -1
+ predictions *= polarity
+
+ error = sum(weights[predictions != y])
+
+ if error < min_error:
+ min_error = error
+ self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))
+ self.threshold = threshold
+ self.feature_index = feature
+ self.polarity = polarity
+
+ def predict(self, X):
+ m = X.shape[0]
+ predictions = np.ones(m)
+ if self.polarity == 1:
+ predictions[X[:, self.feature_index] < self.threshold] = -1
+ else:
+ predictions[X[:, self.feature_index] >= self.threshold] = -1
+ return predictions
+
+class AdaBoost:
+ def fit(self, X, y, n_estimators):
+ m = X.shape[0]
+ self.alphas = []
+ self.models = []
+
+ weights = np.ones(m) / m
+
+ for _ in range(n_estimators):
+ stump = DecisionStump()
+ stump.fit(X, y, weights)
+ predictions = stump.predict(X)
+
+ error = sum(weights[predictions != y])
+ if error == 0:
+ break
+
+ self.models.append(stump)
+ self.alphas.append(stump.alpha)
+
+ weights *= np.exp(-stump.alpha * y * predictions)
+ weights /= np.sum(weights)
+
+ def predict(self, X):
+ final_predictions = np.zeros(X.shape[0])
+ for alpha, model in zip(self.alphas, self.models):
+ final_predictions += alpha * model.predict(X)
+ return np.sign(final_predictions)
+
+# Example dataset (X, y)
+X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
+y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1]) # Labels must be -1 or 1
+
+# Train AdaBoost
+ada = AdaBoost()
+ada.fit(X, y, n_estimators=10)
+
+# Predictions
+predictions = ada.predict(X)
+print("Predictions:", predictions)
+
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
@@ -1233,6 +2963,108 @@ plt.show()
Gradient boosting, making our own code for a regression case
+
+
+
+import numpy as np
+class DecisionTreeRegressor:
+ def __init__(self, max_depth=3):
+ self.max_depth = max_depth
+ self.tree = None
+ def fit(self, X, y):
+ self.tree = self._grow_tree(X, y)
+ def _grow_tree(self, X, y, depth=0):
+ n_samples, n_features = X.shape
+ if depth < self.max_depth:
+ best_feature, best_threshold = self._best_split(X, y)
+ if best_feature is not None:
+ left_indices = X[:, best_feature] < best_threshold
+ right_indices = X[:, best_feature] >= best_threshold
+ left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
+ right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
+ return (best_feature, best_threshold, left_child, right_child)
+ return np.mean(y)
+ def _best_split(self, X, y):
+ best_mse = float('inf')
+ best_feature, best_threshold = None, None
+ n_samples, n_features = X.shape
+
+ for feature in range(n_features):
+ thresholds = np.unique(X[:, feature])
+ for threshold in thresholds:
+ left_indices = X[:, feature] < threshold
+ right_indices = X[:, feature] >= threshold
+ if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
+ left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
+ right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
+ mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
+
+ if mse < best_mse:
+ best_mse = mse
+ best_feature = feature
+ best_threshold = threshold
+ return best_feature, best_threshold
+ def predict(self, X):
+ return np.array([self._predict_sample(sample, self.tree) for sample in X])
+ def _predict_sample(self, sample, node):
+ if isinstance(node, tuple):
+ feature, threshold, left_child, right_child = node
+ if sample[feature] < threshold:
+ return self._predict_sample(sample, left_child)
+ else:
+ return self._predict_sample(sample, right_child)
+ return node
+class GradientBoostingRegressor:
+ def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
+ self.n_estimators = n_estimators
+ self.learning_rate = learning_rate
+ self.max_depth = max_depth
+ self.models = []
+ def fit(self, X, y):
+ y_pred = np.zeros(y.shape)
+ for _ in range(self.n_estimators):
+ residuals = y - y_pred
+ model = DecisionTreeRegressor(max_depth=self.max_depth)
+ model.fit(X, residuals)
+ y_pred += self.learning_rate * model.predict(X)
+ self.models.append(model)
+ def predict(self, X):
+ y_pred = np.zeros(X.shape[0])
+ for model in self.models:
+ y_pred += self.learning_rate * model.predict(X)
+ return y_pred
+# Example usage
+if __name__ == "__main__":
+ # Sample data
+ X = np.array([[1], [2], [3], [4], [5]])
+ y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
+ model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
+ model.fit(X, y)
+ predictions = model.predict(X)
+ print("Predictions:", predictions)
+
+
+
-
+
+Building a tree, regression
+
+
+
+
+A top-down approach, recursive binary splitting
+
+
+Making a tree
+
+Pruning the tree
+
+
+Cost complexity pruning
+
+
+Schematic Regression Procedure
+
+
+
+
+
+
+A Classification Tree
+
+
+Growing a classification tree
+
+
+Classification tree, how to split nodes
+
+
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
+$$
+
+
+
+$$
+g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
+$$
+
+
+
+$$
+s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
+$$
+
+
+
+Visualizing the Tree, Classification
+
+
+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)
+
+
+Visualizing the Tree, The Moons
+
+
+# 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)
+
+
+Other ways of visualizing the trees
+
+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
+
+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)
+
+
+Algorithms for Setting up Decision Trees
+
+
+
+
+The CART algorithm for Classification
+
+
+The CART algorithm for Regression
+
+
+Why binary splits?
+
+
+Computing a Tree using the Gini Index
+
+
+
+
+The Table
+
+
+
+
+
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+ Above Low High Above
+ Below High Low Below
+ Above Low High Above
+ Above High High Above
+ Below Low High Below
+ Above Low Low Below
+ Below High High Below
+ Below Low High Below
+ Above Low Low Below
+
+ Above High High Above
+Computing the various Gini Indices
+
+
+A possible code using Scikit-Learn
+
+
+
+# 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
+
+# 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("grades.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+grades = pd.read_csv(infile)
+grades = pd.DataFrame(grades)
+display(grades)
+# Features and targets
+X = grades.loc[:, grades.columns != 'Grade'].values
+y = grades.loc[:, grades.columns == 'Grade'].values
+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/grade.dot",
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
+os.system(cmd)
+
+
+Further example: Computing the Gini index
+
+
+
+
+
+
+
+
+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
+Simple Python Code to read in Data and perform Classification
+
+
+
+# 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
+
+# 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)
+
+
+Computing the Gini Factor
+
+# 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
+
+# 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']))
+
+
+Regression trees
+
+
+# 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)
+
+
+Final regressor code
+
+
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+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()
+
+
+Pros and cons of trees, pros
+
+
+
+
+Disadvantages
+
+
+
+
+Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
+
+
+
+
+An Overview of Ensemble Methods
+
+
+
+
+
+Why Voting?
+
+
+Tossing coins
+
+
+Standard imports first
+
+
+
+# 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)
+
+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')
+
+
+Simple Voting Example, head or tail
+
+
+# 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()
+
+
+Using the Voting Classifier
+
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+Voting and Bagging
+
+
+
+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))
+
+
+Bagging
+
+
+More bagging
+
+
+Making your own Bootstrap: Changing the Level of the Decision Tree
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
+print("Simple tree:",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()
+
+
+Making an ADAboost code yourself
+
+
+
+import numpy as np
+
+class DecisionStump:
+ def fit(self, X, y, weights):
+ m, n = X.shape
+ self.alpha = 0
+ self.threshold = None
+ self.polarity = 1
+
+ min_error = float('inf')
+
+ for feature in range(n):
+ feature_values = np.unique(X[:, feature])
+
+ for threshold in feature_values:
+ for polarity in [1, -1]:
+ predictions = np.ones(m)
+ predictions[X[:, feature] < threshold] = -1
+ predictions *= polarity
+
+ error = sum(weights[predictions != y])
+
+ if error < min_error:
+ min_error = error
+ self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))
+ self.threshold = threshold
+ self.feature_index = feature
+ self.polarity = polarity
+
+ def predict(self, X):
+ m = X.shape[0]
+ predictions = np.ones(m)
+ if self.polarity == 1:
+ predictions[X[:, self.feature_index] < self.threshold] = -1
+ else:
+ predictions[X[:, self.feature_index] >= self.threshold] = -1
+ return predictions
+
+class AdaBoost:
+ def fit(self, X, y, n_estimators):
+ m = X.shape[0]
+ self.alphas = []
+ self.models = []
+
+ weights = np.ones(m) / m
+
+ for _ in range(n_estimators):
+ stump = DecisionStump()
+ stump.fit(X, y, weights)
+ predictions = stump.predict(X)
+
+ error = sum(weights[predictions != y])
+ if error == 0:
+ break
+
+ self.models.append(stump)
+ self.alphas.append(stump.alpha)
+
+ weights *= np.exp(-stump.alpha * y * predictions)
+ weights /= np.sum(weights)
+
+ def predict(self, X):
+ final_predictions = np.zeros(X.shape[0])
+ for alpha, model in zip(self.alphas, self.models):
+ final_predictions += alpha * model.predict(X)
+ return np.sign(final_predictions)
+
+# Example dataset (X, y)
+X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
+y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1]) # Labels must be -1 or 1
+
+# Train AdaBoost
+ada = AdaBoost()
+ada.fit(X, y, n_estimators=10)
+
+# Predictions
+predictions = ada.predict(X)
+print("Predictions:", predictions)
+
+
Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
@@ -1114,6 +2905,107 @@ plt.show()
+Gradient boosting, making our own code for a regression case
+
+
+
+import numpy as np
+class DecisionTreeRegressor:
+ def __init__(self, max_depth=3):
+ self.max_depth = max_depth
+ self.tree = None
+ def fit(self, X, y):
+ self.tree = self._grow_tree(X, y)
+ def _grow_tree(self, X, y, depth=0):
+ n_samples, n_features = X.shape
+ if depth < self.max_depth:
+ best_feature, best_threshold = self._best_split(X, y)
+ if best_feature is not None:
+ left_indices = X[:, best_feature] < best_threshold
+ right_indices = X[:, best_feature] >= best_threshold
+ left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
+ right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
+ return (best_feature, best_threshold, left_child, right_child)
+ return np.mean(y)
+ def _best_split(self, X, y):
+ best_mse = float('inf')
+ best_feature, best_threshold = None, None
+ n_samples, n_features = X.shape
+
+ for feature in range(n_features):
+ thresholds = np.unique(X[:, feature])
+ for threshold in thresholds:
+ left_indices = X[:, feature] < threshold
+ right_indices = X[:, feature] >= threshold
+ if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
+ left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
+ right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
+ mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
+
+ if mse < best_mse:
+ best_mse = mse
+ best_feature = feature
+ best_threshold = threshold
+ return best_feature, best_threshold
+ def predict(self, X):
+ return np.array([self._predict_sample(sample, self.tree) for sample in X])
+ def _predict_sample(self, sample, node):
+ if isinstance(node, tuple):
+ feature, threshold, left_child, right_child = node
+ if sample[feature] < threshold:
+ return self._predict_sample(sample, left_child)
+ else:
+ return self._predict_sample(sample, right_child)
+ return node
+class GradientBoostingRegressor:
+ def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
+ self.n_estimators = n_estimators
+ self.learning_rate = learning_rate
+ self.max_depth = max_depth
+ self.models = []
+ def fit(self, X, y):
+ y_pred = np.zeros(y.shape)
+ for _ in range(self.n_estimators):
+ residuals = y - y_pred
+ model = DecisionTreeRegressor(max_depth=self.max_depth)
+ model.fit(X, residuals)
+ y_pred += self.learning_rate * model.predict(X)
+ self.models.append(model)
+ def predict(self, X):
+ y_pred = np.zeros(X.shape[0])
+ for model in self.models:
+ y_pred += self.learning_rate * model.predict(X)
+ return y_pred
+# Example usage
+if __name__ == "__main__":
+ # Sample data
+ X = np.array([[1], [2], [3], [4], [5]])
+ y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
+ model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
+ model.fit(X, y)
+ predictions = model.predict(X)
+ print("Predictions:", predictions)
+
+
+
-
+
+Building a tree, regression
+
+
+
+
+A top-down approach, recursive binary splitting
+
+
+Making a tree
+
+Pruning the tree
+
+
+Cost complexity pruning
+
+
+Schematic Regression Procedure
+
+
+
+
+
+
+A Classification Tree
+
+
+Growing a classification tree
+
+
+Classification tree, how to split nodes
+
+
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
+$$
+
+
+
+$$
+g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
+$$
+
+
+
+$$
+s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
+$$
+
+
+
+Visualizing the Tree, Classification
+
+
+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)
+
+
+Visualizing the Tree, The Moons
+
+
+# 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)
+
+
+Other ways of visualizing the trees
+
+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
+
+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)
+
+
+Algorithms for Setting up Decision Trees
+
+
+
+
+The CART algorithm for Classification
+
+
+The CART algorithm for Regression
+
+
+Why binary splits?
+
+
+Computing a Tree using the Gini Index
+
+
+
+
+The Table
+
+
+
+
+
+
+
+
+Grade Trend Hours slept Hours Studied Grade
+ Above Low High Above
+ Below High Low Below
+ Above Low High Above
+ Above High High Above
+ Below Low High Below
+ Above Low Low Below
+ Below High High Below
+ Below Low High Below
+ Above Low Low Below
+
+ Above High High Above
+Computing the various Gini Indices
+
+
+A possible code using Scikit-Learn
+
+
+
+# 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
+
+# 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("grades.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+grades = pd.read_csv(infile)
+grades = pd.DataFrame(grades)
+display(grades)
+# Features and targets
+X = grades.loc[:, grades.columns != 'Grade'].values
+y = grades.loc[:, grades.columns == 'Grade'].values
+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/grade.dot",
+ rounded=True,
+ filled=True
+)
+cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
+os.system(cmd)
+
+
+Further example: Computing the Gini index
+
+
+
+
+
+
+
+
+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
+Simple Python Code to read in Data and perform Classification
+
+
+
+# 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
+
+# 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)
+
+
+Computing the Gini Factor
+
+# 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
+
+# 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']))
+
+
+Regression trees
+
+
+# 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)
+
+
+Final regressor code
+
+
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+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()
+
+
+Pros and cons of trees, pros
+
+
+
+
+Disadvantages
+
+
+
+
+Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
+
+
+
+
+An Overview of Ensemble Methods
+
+
+
+
+
+Why Voting?
+
+
+Tossing coins
+
+
+Standard imports first
+
+
+
+# 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)
+
+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')
+
+
+Simple Voting Example, head or tail
+
+
+# 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()
+
+
+Using the Voting Classifier
+
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+Voting and Bagging
+
+
+
+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))
+
+
+Bagging
+
+
+More bagging
+
+
+Making your own Bootstrap: Changing the Level of the Decision Tree
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train_scaled, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
+print("Simple tree:",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()
+
+
+Making an ADAboost code yourself
+
+
+
+import numpy as np
+
+class DecisionStump:
+ def fit(self, X, y, weights):
+ m, n = X.shape
+ self.alpha = 0
+ self.threshold = None
+ self.polarity = 1
+
+ min_error = float('inf')
+
+ for feature in range(n):
+ feature_values = np.unique(X[:, feature])
+
+ for threshold in feature_values:
+ for polarity in [1, -1]:
+ predictions = np.ones(m)
+ predictions[X[:, feature] < threshold] = -1
+ predictions *= polarity
+
+ error = sum(weights[predictions != y])
+
+ if error < min_error:
+ min_error = error
+ self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))
+ self.threshold = threshold
+ self.feature_index = feature
+ self.polarity = polarity
+
+ def predict(self, X):
+ m = X.shape[0]
+ predictions = np.ones(m)
+ if self.polarity == 1:
+ predictions[X[:, self.feature_index] < self.threshold] = -1
+ else:
+ predictions[X[:, self.feature_index] >= self.threshold] = -1
+ return predictions
+
+class AdaBoost:
+ def fit(self, X, y, n_estimators):
+ m = X.shape[0]
+ self.alphas = []
+ self.models = []
+
+ weights = np.ones(m) / m
+
+ for _ in range(n_estimators):
+ stump = DecisionStump()
+ stump.fit(X, y, weights)
+ predictions = stump.predict(X)
+
+ error = sum(weights[predictions != y])
+ if error == 0:
+ break
+
+ self.models.append(stump)
+ self.alphas.append(stump.alpha)
+
+ weights *= np.exp(-stump.alpha * y * predictions)
+ weights /= np.sum(weights)
+
+ def predict(self, X):
+ final_predictions = np.zeros(X.shape[0])
+ for alpha, model in zip(self.alphas, self.models):
+ final_predictions += alpha * model.predict(X)
+ return np.sign(final_predictions)
+
+# Example dataset (X, y)
+X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
+y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1]) # Labels must be -1 or 1
+
+# Train AdaBoost
+ada = AdaBoost()
+ada.fit(X, y, n_estimators=10)
+
+# Predictions
+predictions = ada.predict(X)
+print("Predictions:", predictions)
+
+
Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
@@ -1191,6 +2982,107 @@ plt.show()
+Gradient boosting, making our own code for a regression case
+
+
+
+import numpy as np
+class DecisionTreeRegressor:
+ def __init__(self, max_depth=3):
+ self.max_depth = max_depth
+ self.tree = None
+ def fit(self, X, y):
+ self.tree = self._grow_tree(X, y)
+ def _grow_tree(self, X, y, depth=0):
+ n_samples, n_features = X.shape
+ if depth < self.max_depth:
+ best_feature, best_threshold = self._best_split(X, y)
+ if best_feature is not None:
+ left_indices = X[:, best_feature] < best_threshold
+ right_indices = X[:, best_feature] >= best_threshold
+ left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
+ right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
+ return (best_feature, best_threshold, left_child, right_child)
+ return np.mean(y)
+ def _best_split(self, X, y):
+ best_mse = float('inf')
+ best_feature, best_threshold = None, None
+ n_samples, n_features = X.shape
+
+ for feature in range(n_features):
+ thresholds = np.unique(X[:, feature])
+ for threshold in thresholds:
+ left_indices = X[:, feature] < threshold
+ right_indices = X[:, feature] >= threshold
+ if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
+ left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
+ right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
+ mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
+
+ if mse < best_mse:
+ best_mse = mse
+ best_feature = feature
+ best_threshold = threshold
+ return best_feature, best_threshold
+ def predict(self, X):
+ return np.array([self._predict_sample(sample, self.tree) for sample in X])
+ def _predict_sample(self, sample, node):
+ if isinstance(node, tuple):
+ feature, threshold, left_child, right_child = node
+ if sample[feature] < threshold:
+ return self._predict_sample(sample, left_child)
+ else:
+ return self._predict_sample(sample, right_child)
+ return node
+class GradientBoostingRegressor:
+ def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
+ self.n_estimators = n_estimators
+ self.learning_rate = learning_rate
+ self.max_depth = max_depth
+ self.models = []
+ def fit(self, X, y):
+ y_pred = np.zeros(y.shape)
+ for _ in range(self.n_estimators):
+ residuals = y - y_pred
+ model = DecisionTreeRegressor(max_depth=self.max_depth)
+ model.fit(X, residuals)
+ y_pred += self.learning_rate * model.predict(X)
+ self.models.append(model)
+ def predict(self, X):
+ y_pred = np.zeros(X.shape[0])
+ for model in self.models:
+ y_pred += self.learning_rate * model.predict(X)
+ return y_pred
+# Example usage
+if __name__ == "__main__":
+ # Sample data
+ X = np.array([[1], [2], [3], [4], [5]])
+ y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
+ model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
+ model.fit(X, y)
+ predictions = model.predict(X)
+ print("Predictions:", predictions)
+
+\n",
+ "\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "20fe13e0",
+ "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.**\n",
+ "\n",
+ "See whiteboard notes from lecture November 11 at \n",
+ "\n",
+ "\n",
+ "Grade Trend Hours slept Hours Studied Grade \n",
+ " Above Low High Above \n",
+ " Below High Low Below \n",
+ " Above Low High Above \n",
+ " Above High High Above \n",
+ " Below Low High Below \n",
+ " Above Low Low Below \n",
+ " Below High High Below \n",
+ " Below Low High Below \n",
+ " Above Low Low Below \n",
+ "\n",
+ " Above High High Above \n",
+ "\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ec8cfb80",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Simple Python Code to read in Data and perform Classification"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "a46e6786",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.tree import export_graphviz\n",
+ "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
+ "from sklearn.compose import ColumnTransformer\n",
+ "from IPython.display import Image \n",
+ "from pydot import graph_from_dot_data\n",
+ "import os\n",
+ "\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
+ "\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
+ "\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"rideclass.csv\"),'r')\n",
+ "\n",
+ "# Read the experimental data with Pandas\n",
+ "from IPython.display import display\n",
+ "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n",
+ "ridedata = pd.DataFrame(ridedata)\n",
+ "\n",
+ "# Features and targets\n",
+ "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n",
+ "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n",
+ "\n",
+ "# Create the encoder.\n",
+ "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n",
+ "# Assume for simplicity all features are categorical.\n",
+ "encoder.fit(X) \n",
+ "# Apply the encoder.\n",
+ "X = encoder.transform(X)\n",
+ "print(X)\n",
+ "# Then do a Classification tree\n",
+ "tree_clf = DecisionTreeClassifier(max_depth=2)\n",
+ "tree_clf.fit(X, y)\n",
+ "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n",
+ "#transfer to a decision tree graph\n",
+ "export_graphviz(\n",
+ " tree_clf,\n",
+ " out_file=\"DataFiles/ride.dot\",\n",
+ " rounded=True,\n",
+ " filled=True\n",
+ ")\n",
+ "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
+ "os.system(cmd)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c2b31b1e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Computing the Gini Factor\n",
+ "\n",
+ "The above functions (gini, entropy and misclassification error) are\n",
+ "important components of the so-called CART algorithm. We will discuss\n",
+ "this algorithm below after we have discussed the information gain\n",
+ "algorithm ID3.\n",
+ "\n",
+ "In the example here we have converted all our attributes into numerical values $0,1,2$ etc."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "ca7473c6",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Split a dataset based on an attribute and an attribute value\n",
+ "def test_split(index, value, dataset):\n",
+ "\tleft, right = list(), list()\n",
+ "\tfor row in dataset:\n",
+ "\t\tif row[index] < value:\n",
+ "\t\t\tleft.append(row)\n",
+ "\t\telse:\n",
+ "\t\t\tright.append(row)\n",
+ "\treturn left, right\n",
+ " \n",
+ "# Calculate the Gini index for a split dataset\n",
+ "def gini_index(groups, classes):\n",
+ "\t# count all samples at split point\n",
+ "\tn_instances = float(sum([len(group) for group in groups]))\n",
+ "\t# sum weighted Gini index for each group\n",
+ "\tgini = 0.0\n",
+ "\tfor group in groups:\n",
+ "\t\tsize = float(len(group))\n",
+ "\t\t# avoid divide by zero\n",
+ "\t\tif size == 0:\n",
+ "\t\t\tcontinue\n",
+ "\t\tscore = 0.0\n",
+ "\t\t# score the group based on the score for each class\n",
+ "\t\tfor class_val in classes:\n",
+ "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n",
+ "\t\t\tscore += p * p\n",
+ "\t\t# weight the group score by its relative size\n",
+ "\t\tgini += (1.0 - score) * (size / n_instances)\n",
+ "\treturn gini\n",
+ "\n",
+ "# Select the best split point for a dataset\n",
+ "def get_split(dataset):\n",
+ "\tclass_values = list(set(row[-1] for row in dataset))\n",
+ "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n",
+ "\tfor index in range(len(dataset[0])-1):\n",
+ "\t\tfor row in dataset:\n",
+ "\t\t\tgroups = test_split(index, row[index], dataset)\n",
+ "\t\t\tgini = gini_index(groups, class_values)\n",
+ "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n",
+ "\t\t\tif gini < b_score:\n",
+ "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n",
+ "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n",
+ " \n",
+ "dataset = [[0,0,0,0,0],\n",
+ " [0,0,0,1,1],\n",
+ " [1,0,0,0,1],\n",
+ " [2,1,0,0,1],\n",
+ " [2,2,1,0,1],\n",
+ " [2,2,1,1,0],\n",
+ " [1,2,1,1,1],\n",
+ " [0,1,0,0,0],\n",
+ " [0,2,1,0,1],\n",
+ " [2,1,1,0,1],\n",
+ " [0,1,1,1,1],\n",
+ " [1,1,0,1,1],\n",
+ " [1,0,1,0,1],\n",
+ " [2,1,0,1,0]]\n",
+ "\n",
+ "split = get_split(dataset)\n",
+ "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3f5c14cf",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Regression trees"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "0c1057e7",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Quadratic training set + noise\n",
+ "np.random.seed(42)\n",
+ "m = 200\n",
+ "X = np.random.rand(m, 1)\n",
+ "y = 4 * (X - 0.5) ** 2\n",
+ "y = y + np.random.randn(m, 1) / 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "17a775d7",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n",
+ "tree_reg.fit(X, y)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b91522ff",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Final regressor code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "485e7be4",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n",
+ " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n",
+ " y_pred = tree_reg.predict(x1)\n",
+ " plt.axis(axes)\n",
+ " plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ " if ylabel:\n",
+ " plt.ylabel(ylabel, fontsize=18, rotation=0)\n",
+ " plt.plot(X, y, \"b.\")\n",
+ " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_regression_predictions(tree_reg1, X, y)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n",
+ "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n",
+ "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"max_depth=2\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n",
+ " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n",
+ "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n",
+ "plt.title(\"max_depth=3\", fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "9a686cbe",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "tree_reg1 = DecisionTreeRegressor(random_state=42)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n",
+ "y_pred1 = tree_reg1.predict(x1)\n",
+ "y_pred2 = tree_reg2.predict(x1)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"No restrictions\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4305a9c8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Pros and cons of trees, pros\n",
+ "\n",
+ "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n",
+ "\n",
+ "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n",
+ "\n",
+ "* No feature normalization needed\n",
+ "\n",
+ "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n",
+ "\n",
+ "* Can model nonlinear relationships\n",
+ "\n",
+ "* Can model interactions between the different descriptive features\n",
+ "\n",
+ "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cee5ffaa",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Disadvantages\n",
+ "\n",
+ "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
+ "\n",
+ "* If continuous features are used the tree may become quite large and hence less interpretable\n",
+ "\n",
+ "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n",
+ "\n",
+ "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n",
+ "\n",
+ "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n",
+ "\n",
+ "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n",
+ "\n",
+ "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n",
+ "\n",
+ "However, by aggregating many decision trees, using methods like\n",
+ "bagging, random forests, and boosting, the predictive performance of\n",
+ "trees can be substantially improved."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1b09495e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## 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",
+ "a single decision tree, we often end up overfitting our training\n",
+ "data. This normally means that we have a high variance. Can we reduce\n",
+ "the variance of a statistical learning method?\n",
+ "\n",
+ "This leads us to a set of different methods that can combine different\n",
+ "machine learning algorithms or just use one of them to construct\n",
+ "forests and jungles of trees, homogeneous ones or heterogenous\n",
+ "ones. These methods are recognized by different names which we will\n",
+ "try to explain here. These are\n",
+ "\n",
+ "1. Voting classifiers\n",
+ "\n",
+ "2. Bagging and Pasting\n",
+ "\n",
+ "3. Random forests\n",
+ "\n",
+ "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n",
+ "\n",
+ "We discuss these methods here."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f0b540cb",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## An Overview of Ensemble Methods\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ " \n",
+ "\n",
+ "\n",
+ "Day Outlook Temperature Humidity Wind Ride \n",
+ " 1 Sunny Hot High Weak 0 \n",
+ " 2 Sunny Hot High Strong 1 \n",
+ " 3 Overcast Hot High Weak 1 \n",
+ " 4 Rain Mild High Weak 1 \n",
+ " 5 Rain Cool Normal Weak 1 \n",
+ " 6 Rain Cool Normal Strong 0 \n",
+ " 7 Overcast Cool Normal Strong 1 \n",
+ " 8 Sunny Mild High Weak 0 \n",
+ " 9 Sunny Cool Normal Weak 1 \n",
+ " 10 Rain Mild Normal Weak 1 \n",
+ " 11 Sunny Mild Normal Strong 1 \n",
+ " 12 Overcast Mild High Strong 1 \n",
+ " 13 Overcast Hot Normal Weak 1 \n",
+ "\n",
+ " 14 Rain Mild High Strong 0 