From 7413b1f1664286c4ac875a3a548f85baba9424a9 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sat, 16 Nov 2024 11:41:19 +0100 Subject: [PATCH] Update week47.do.txt --- doc/src/week47/week47.do.txt | 1227 +++++++++++++++++++++++++++++++++- 1 file changed, 1220 insertions(+), 7 deletions(-) diff --git a/doc/src/week47/week47.do.txt b/doc/src/week47/week47.do.txt index a7ff8baf5..218a20118 100644 --- a/doc/src/week47/week47.do.txt +++ b/doc/src/week47/week47.do.txt @@ -11,20 +11,1233 @@ DATE: November 18-22, 2024 * Second last weekly exercise, !eblock -!bblock Material for the lecture Monday 18 November +!bblock Plans for the lecture Monday 18 November, with video suggestions etc o Basics of decision trees, classification and regression algorithms and ensemble models o Readings and Videos: - * These lecture notes + o These lecture notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week47.ipynb" + o See also lecture notes from week 46 at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week46.ipynb" # * "Video of Lecture":"https://youtu.be/SpWXsvn5I9E" # * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesNov23.pdf" - * Video on Decision trees URL:"https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" - * Video on boosting methods URL:"https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai" - * Video on AdaBoost URL:"https://www.youtube.com/watch?v=LsK-xG1cLYA" - * Video on Gradient boost, part 1, parts 2-4 follow thereafter URL:"https://www.youtube.com/watch?v=3CC4N4z3GJc" - * Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from "STK-IN4300, lecture 7":"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf". Chapter 9.2 of Hastie et al contains also a good discussion. + o Video on Decision trees URL:"https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" + o Video on boosting methods URL:"https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai" + o Video on AdaBoost URL:"https://www.youtube.com/watch?v=LsK-xG1cLYA" + o Video on Gradient boost, part 1, parts 2-4 follow thereafter URL:"https://www.youtube.com/watch?v=3CC4N4z3GJc" + o Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at URL:"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf". +* Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from "STK-IN4300, lecture 7":"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf". Chapter 9.2 of Hastie et al contains also a good discussion. !eblock +!split +===== Building a tree, regression ===== + +There are mainly two steps +o We split the predictor space (the set of possible values $x_1,x_2,\dots, x_p$) into $J$ distinct and non-non-overlapping regions, $R_1,R_2,\dots,R_J$. +o For every observation that falls into the region $R_j$ , we make the same prediction, which is simply the mean of the response values for the training observations in $R_j$. + +How do we construct the regions $R_1,\dots,R_J$? In theory, the +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 + +!bt +\[ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +\] +!et + +where $\overline{y}_{R_j}$ is the mean response for the training observations +within box $j$. + +!split +===== A top-down approach, recursive binary splitting ===== + +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. + +!split +===== Making a tree ===== + +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$ +!bt +\[ +\left\{X\vert x_j < s\right\}, +\] +!et +and +!bt +\[ +\left\{X\vert x_j \geq s\right\}, +\] +!et +so that we obtain the lowest MSE, that is +!bt +\[ +\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, +\] +!et + +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. + +!split +===== Pruning the tree ===== + +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":"https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py". + +!split +===== Cost complexity pruning ===== + +For each value of $\alpha$ there corresponds a subtree $T \in T_0$ such that +!bt +\[ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +\] +!et +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$. + + +!split +===== Schematic Regression Procedure ===== + +!bblock Building a Regression Tree + +o Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations. +o Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\alpha$. +o Use for example $K$-fold cross-validation to choose $\alpha$. Divide the training observations into $K$ folds. For each $k=1,2,\dots,K$ we: + * repeat steps 1 and 2 on all but the $k$-th fold of the training data. + * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\alpha$. + * Finally we average the results for each value of $\alpha$, and pick $\alpha$ to minimize the average error. +o Return the subtree from Step 2 that corresponds to the chosen value of $\alpha$. +!eblock + + +!split +===== A Classification Tree ===== + +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. + +!split +===== Growing a classification tree ===== + +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. + + +!split +===== Classification tree, how to split nodes ===== + +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 + +!bt +\[ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +\] +!et + +We let $p_{mk}$ represent the majority class of observations in region +$m$. The three most common ways of splitting a node are given by + +* Misclassification error +!bt +\[ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +\] +!et +* Gini index $g$ +!bt +\[ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +\] +!et +* Information entropy or just entropy $s$ +!bt +\[ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +\] +!et + + +!split +===== Visualizing the Tree, Classification ===== +!bc pycod +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) +!ec + +!split +===== Visualizing the Tree, The Moons ===== +!bc pycod +# 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) +!ec + +!split +===== Other ways of visualizing the trees ===== + +_Scikit-Learn_ has also another way to visualize the trees which is very useful, here with the Iris data. + +!bc pycod +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) +!ec + +!split +===== Printing out as text ===== + +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: + +!bc pycod +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) +!ec + + +!split +===== Algorithms for Setting up Decision Trees ===== + +Two algorithms stand out in the set up of decision trees: +o The CART (Classification And Regression Tree) algorithm for both classification and regression +o The ID3 algorithm based on the computation of the information gain for classification + +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. + +!split +===== The CART algorithm for Classification ===== + +For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$. +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 +!bt +\[ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +\] +!et +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$. + +!split +===== The CART algorithm for Regression ===== + +The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +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 +!bt +\[ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +\] +!et +Here the MSE for a specific node is defined as +!bt +\[ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +\] +!et +with +!bt +\[ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +\] +!et +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. + +!split +===== Why binary splits? ===== + +It is custom to split to a tree uising binary splits. The reason is +that multiway splits fragment the data too quickly, leaving +insufficient data at the next level down. Multiway splits can be +achieved by a series of binary split and this is normally preferred. + + +!split +===== Computing a Tree using the Gini Index ===== + +Consider the following example with attributes/features and two +possible outcomes (classes) for each attribute. Assume we wish to find some +correlations between the average grade of a student as function of the +number of hours studied and hours slept. We want also to correlate the +grade in a given course with the general trend, whether the students +recently has gotten grades below average or above. + +We have three features/attributes +o Trend of average grades before present course, classified as either below or above the average grade of the whole class +o The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one $ECTS$ which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester. +o The number of hours slept as high for more than $8$ hours and below for less than 8 hours of sleep, classified again as either high or low +o The final grade whether it is above or below average + + +!split +===== The Table ===== + +|---------------------------------------------------| +| Grade Trend | Hours slept | Hours Studied | Grade | +|---------------------------------------------------| +| 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 | +|---------------------------------------------------| + + +!split +===== Computing the various Gini Indices ===== + +In computations we will translate all classes into numbers. Being +these binary classes, they can easily be split into ones and zeros. + +!bblock Gini index for Average trend +"See handwritten notes November 3":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" +!eblock + + +!split +===== Computing the various Gini Indices, Hours slept ===== + + +!bblock Gini index for hour slept +"See handwritten notes November 3":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" +!eblock + + +!split +===== Computing the various Gini Indices, Hours studied ===== + + +!bblock Gini index for hour studied +"See handwritten notes November 3":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" +!eblock + +For final tree, see the above handwritten notes + + +!split +===== A possible code using Scikit-Learn ===== + +!bc pycod +# 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) + + +!ec + + + +!split +===== Further example: Computing the Gini index ===== + +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 +|-------------------------------------------| +|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 | +|-------------------------------------------| + + +!split +===== Simple Python Code to read in Data and perform Classification ===== + +!bc pycod +# 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) + + +!ec + +!split +===== Computing the Gini Factor ===== + +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. + +!bc pycod +# 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'])) +!ec + + + +!split +===== Regression trees ===== +!bc pycod +# Quadratic training set + noise +np.random.seed(42) +m = 200 +X = np.random.rand(m, 1) +y = 4 * (X - 0.5) ** 2 +y = y + np.random.randn(m, 1) / 10 +!ec + +!bc pycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg.fit(X, y) +!ec + +!split +===== Final regressor code ===== +!bc pycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) +tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): + x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) + y_pred = tree_reg.predict(x1) + plt.axis(axes) + plt.xlabel("$x_1$", fontsize=18) + if ylabel: + plt.ylabel(ylabel, fontsize=18, rotation=0) + plt.plot(X, y, "b.") + plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_regression_predictions(tree_reg1, X, y) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +plt.text(0.21, 0.65, "Depth=0", fontsize=15) +plt.text(0.01, 0.2, "Depth=1", fontsize=13) +plt.text(0.65, 0.8, "Depth=1", fontsize=13) +plt.legend(loc="upper center", fontsize=18) +plt.title("max_depth=2", fontsize=14) + +plt.subplot(122) +plot_regression_predictions(tree_reg2, X, y, ylabel=None) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +for split in (0.0458, 0.1298, 0.2873, 0.9040): + plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) +plt.text(0.3, 0.5, "Depth=2", fontsize=13) +plt.title("max_depth=3", fontsize=14) + +plt.show() +!ec + +!bc pycod +tree_reg1 = DecisionTreeRegressor(random_state=42) +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +x1 = np.linspace(0, 1, 500).reshape(-1, 1) +y_pred1 = tree_reg1.predict(x1) +y_pred2 = tree_reg2.predict(x1) + +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.ylabel("$y$", fontsize=18, rotation=0) +plt.legend(loc="upper center", fontsize=18) +plt.title("No restrictions", fontsize=14) + +plt.subplot(122) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) + +plt.show() +!ec + + + + +!split +===== Pros and cons of trees, pros ===== + +* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines) +* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! +* No feature normalization needed +* Tree models can handle both continuous and categorical data (Classification and Regression Trees) +* Can model nonlinear relationships +* Can model interactions between the different descriptive features +* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) + + +!split +===== Disadvantages ===== + +* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches +* If continuous features are used the tree may become quite large and hence less interpretable +* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented +* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests +* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. +* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data +* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain + +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. + + +!split +===== Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods ===== + +As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +o Voting classifiers +o Bagging and Pasting +o Random forests +o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) + +We discuss these methods here. + + +!split +===== An Overview of Ensemble Methods ===== + +FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8] + +!split +===== Why Voting? ===== + +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. + +!split +===== Tossing coins ===== + +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":"https://en.wikipedia.org/wiki/Law_of_large_numbers" +numbers kicking in. + +!split +===== Standard imports first ===== + +!bc pycod +# 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') + +!ec + + + + +!split +===== Simple Voting Example, head or tail ===== +!bc pycod + +# 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() + +!ec + + +!split +===== Using the Voting Classifier ===== + +We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of _Scikit-Learn_. +!bc pycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') + +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", probability=True, random_state=42) +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +!ec + + + + +!split +===== Voting and Bagging ===== + +!bc pycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') +voting_clf.fit(X_train, y_train) +!ec + +!bc pycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +!ec + +!bc pycod +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) +!ec + +!bc pycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +!ec + + + + + +!split +===== Bagging ===== + +The _plain_ decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of $n$ to $p$ is moderately large. + +_Bootstrap aggregation_, or just _bagging_, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + + +!split +===== More bagging ===== + +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all $B$ possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all $B$ trees. + + + +!split +===== Making your own Bootstrap: Changing the Level of the Decision Tree ===== + +Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$). +!bc pycod + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + +n = 100 +n_boostraps = 100 +maxdepth = 8 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdepth) +bias = np.zeros(maxdepth) +variance = np.zeros(maxdepth) +polydegree = np.zeros(maxdepth) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +# we produce a simple tree first as benchmark +simpletree = DecisionTreeRegressor(max_depth=3) +simpletree.fit(X_train_scaled, y_train) +simpleprediction = simpletree.predict(X_test_scaled) +for degree in range(1,maxdepth): + model = DecisionTreeRegressor(max_depth=degree) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)) +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() + +!ec + + + + !split