From 7e5333fb904dfe6bc6746ab8ae1628df2f308e7b Mon Sep 17 00:00:00 2001 From: mhjensen Date: Fri, 25 Oct 2019 11:56:56 +0200 Subject: [PATCH] added material about id3 also --- .../html/._DecisionTrees-bs000.html | 114 ++++----- .../html/._DecisionTrees-bs001.html | 114 ++++----- .../html/._DecisionTrees-bs002.html | 134 +++++------ .../html/._DecisionTrees-bs003.html | 214 ++++++----------- .../html/._DecisionTrees-bs004.html | 220 ++++++++++++------ .../html/._DecisionTrees-bs005.html | 145 ++++++------ .../html/._DecisionTrees-bs006.html | 164 ++++++------- .../html/._DecisionTrees-bs007.html | 166 +++++++------ .../html/._DecisionTrees-bs008.html | 150 ++++++------ .../html/._DecisionTrees-bs009.html | 158 +++++++------ .../html/._DecisionTrees-bs010.html | 148 ++++++------ .../html/._DecisionTrees-bs011.html | 145 ++++++------ .../html/._DecisionTrees-bs012.html | 166 ++++++------- .../html/._DecisionTrees-bs013.html | 154 +++++++----- .../html/._DecisionTrees-bs014.html | 185 +++++++-------- .../html/._DecisionTrees-bs015.html | 184 +++++---------- .../html/._DecisionTrees-bs016.html | 173 ++++++++------ .../html/._DecisionTrees-bs017.html | 188 +++++++++------ .../html/._DecisionTrees-bs018.html | 190 ++++++--------- .../html/._DecisionTrees-bs019.html | 142 ++++++----- .../html/._DecisionTrees-bs020.html | 198 ++++++++++------ .../html/._DecisionTrees-bs021.html | 163 ++++++------- .../html/._DecisionTrees-bs022.html | 143 ++++++------ .../html/._DecisionTrees-bs023.html | 175 +++++++------- .../html/._DecisionTrees-bs024.html | 138 +++++------ .../html/._DecisionTrees-bs025.html | 190 +++++++-------- .../html/._DecisionTrees-bs026.html | 179 ++++++-------- .../html/._DecisionTrees-bs027.html | 172 ++++++++------ .../html/._DecisionTrees-bs028.html | 175 +++++++++----- .../html/._DecisionTrees-bs029.html | 141 ++++++----- .../html/._DecisionTrees-bs030.html | 46 ++-- .../DecisionTrees/html/DecisionTrees-bs.html | 114 ++++----- .../html/DecisionTrees-reveal.html | 112 ++++++--- .../html/DecisionTrees-solarized.html | 166 ++++++++----- doc/pub/DecisionTrees/html/DecisionTrees.html | 166 ++++++++----- .../DecisionTrees/ipynb/DecisionTrees.ipynb | 49 +++- .../ipynb/ipynb-DecisionTrees-src.tar.gz | Bin 194 -> 194 bytes .../pdf/DecisionTrees-minted.pdf | Bin 262491 -> 265097 bytes doc/src/DecisionTrees/DecisionTrees.do.txt | 44 +++- 39 files changed, 3034 insertions(+), 2591 deletions(-) diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html index a1f2bc91d..60b829003 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -198,7 +202,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html index d62144044..f172e5af7 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -203,7 +207,7 @@ and leaf nodes which are then connected by branches.
  • 10
  • 11
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html index 0ebae0fe3..d8d12de75 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,20 +159,20 @@ MathJax.Hub.Config({ -

    How do we set it up?

    +

    General Features

    -In simplified terms, the process of training a decision tree and -predicting the target features of query instances is as follows: +Decision trees classify instances by sorting top down. -

      -
    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. -
    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. -
    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. -
    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. -
    + -Then we are essentially done! +This processis then repeated for the subtree rooted at the new +node.

    @@ -188,7 +192,7 @@ Then we are essentially done!

  • 11
  • 12
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html index 122519571..55172e31d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,99 +159,21 @@ MathJax.Hub.Config({ -

    Decision trees and Regression

    +

    How do we set it up?

    +

    +In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    +
      +
    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. +
    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. +
    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. +
    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. +
    -steps=250 +Then we are essentially done! -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x<steps: - distance+=np.random.randint(-1,2) - distance_list.append(distance) - x+=1 - steps_list.append(x) -plt.plot(steps_list,distance_list, color='green', label="Random Walk Data") - -steps_list=np.asarray(steps_list) -distance_list=np.asarray(distance_list) - -X=steps_list[:,np.newaxis] - -#Polynomial fits - -#Degree 2 -poly_features=PolynomialFeatures(degree=2, include_bias=False) -X_poly=poly_features.fit_transform(X) - -lin_reg=LinearRegression() -poly_fit=lin_reg.fit(X_poly,distance_list) -b=lin_reg.coef_ -c=lin_reg.intercept_ -print ("2nd degree coefficients:") -print ("zero power: ",c) -print ("first power: ", b[0]) -print ("second power: ",b[1]) - -z = np.arange(0, steps, .01) -z_mod=b[1]*z**2+b[0]*z+c - -fit_mod=b[1]*X**2+b[0]*X+c -plt.plot(z, z_mod, color='r', label="2nd Degree Fit") -plt.title("Polynomial Regression") - -plt.xlabel("Steps") -plt.ylabel("Distance") - -#Degree 10 -poly_features10=PolynomialFeatures(degree=10, include_bias=False) -X_poly10=poly_features10.fit_transform(X) - -poly_fit10=lin_reg.fit(X_poly10,distance_list) - -y_plot=poly_fit10.predict(X_poly10) -plt.plot(X, y_plot, color='black', label="10th Degree Fit") - -plt.legend() -plt.show() - - -#Decision Tree Regression -from sklearn.tree import DecisionTreeRegressor -regr_1=DecisionTreeRegressor(max_depth=2) -regr_2=DecisionTreeRegressor(max_depth=5) -regr_3=DecisionTreeRegressor(max_depth=7) -regr_1.fit(X, distance_list) -regr_2.fit(X, distance_list) -regr_3.fit(X, distance_list) - -X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis] -y_1 = regr_1.predict(X_test) -y_2 = regr_2.predict(X_test) -y_3=regr_3.predict(X_test) - -# Plot the results -plt.figure() -plt.scatter(X, distance_list, s=2.5, c="black", label="data") -plt.plot(X_test, y_1, color="red", - label="max_depth=2", linewidth=2) -plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2) -plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2) - -plt.xlabel("Data") -plt.ylabel("Darget") -plt.title("Decision Tree Regression") -plt.legend() -plt.show() -

    @@ -267,7 +193,7 @@ plt.show()

  • 12
  • 13
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html index a9383aaee..1f1af5517 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,29 +159,99 @@ MathJax.Hub.Config({ -

    Building a tree, regression

    - +

    Decision trees and Regression

    -There are mainly two steps -

      -
    1. 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 \).
    2. -
    3. 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 \).
    4. -
    + +
    import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn.preprocessing import PolynomialFeatures
    +from sklearn.linear_model import LinearRegression
     
    -How do we construct the regions \( R_1,\dots,R_J \)? 
    -In theory, the regions could have any shape. However, we
    -choose to divide the predictor space into high-dimensional rectangles,
    -or boxes, for simplicity and for ease of interpretation of the
    -resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \) 
    -that minimize the MSE, given by 
    -$$
    -\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
    -$$
    +steps=250
     
    -where \( \overline{y}_{R_j} \)  is the mean response for the training observations 
    -within box \( j \).
    +distance=0
    +x=0
    +distance_list=[]
    +steps_list=[]
    +while x<steps:
    +    distance+=np.random.randint(-1,2)
    +    distance_list.append(distance)
    +    x+=1
    +    steps_list.append(x)
    +plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
     
    +steps_list=np.asarray(steps_list)
    +distance_list=np.asarray(distance_list)
    +
    +X=steps_list[:,np.newaxis]
    +
    +#Polynomial fits
    +
    +#Degree 2
    +poly_features=PolynomialFeatures(degree=2, include_bias=False)
    +X_poly=poly_features.fit_transform(X)
    +
    +lin_reg=LinearRegression()
    +poly_fit=lin_reg.fit(X_poly,distance_list)
    +b=lin_reg.coef_
    +c=lin_reg.intercept_
    +print ("2nd degree coefficients:")
    +print ("zero power: ",c)
    +print ("first power: ", b[0])
    +print ("second power: ",b[1])
    +
    +z = np.arange(0, steps, .01)
    +z_mod=b[1]*z**2+b[0]*z+c
    +
    +fit_mod=b[1]*X**2+b[0]*X+c
    +plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
    +plt.title("Polynomial Regression")
    +
    +plt.xlabel("Steps")
    +plt.ylabel("Distance")
    +
    +#Degree 10
    +poly_features10=PolynomialFeatures(degree=10, include_bias=False)
    +X_poly10=poly_features10.fit_transform(X)
    +
    +poly_fit10=lin_reg.fit(X_poly10,distance_list)
    +
    +y_plot=poly_fit10.predict(X_poly10)
    +plt.plot(X, y_plot, color='black', label="10th Degree Fit")
    +
    +plt.legend()
    +plt.show()
    +
    +
    +#Decision Tree Regression
    +from sklearn.tree import DecisionTreeRegressor
    +regr_1=DecisionTreeRegressor(max_depth=2)
    +regr_2=DecisionTreeRegressor(max_depth=5)
    +regr_3=DecisionTreeRegressor(max_depth=7)
    +regr_1.fit(X, distance_list)
    +regr_2.fit(X, distance_list)
    +regr_3.fit(X, distance_list)
    +
    +X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
    +y_1 = regr_1.predict(X_test)
    +y_2 = regr_2.predict(X_test)
    +y_3=regr_3.predict(X_test)
    +
    +# Plot the results
    +plt.figure()
    +plt.scatter(X, distance_list, s=2.5, c="black", label="data")
    +plt.plot(X_test, y_1, color="red",
    +         label="max_depth=2", linewidth=2)
    +plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
    +plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
    +
    +plt.xlabel("Data")
    +plt.ylabel("Darget")
    +plt.title("Decision Tree Regression")
    +plt.legend()
    +plt.show()
    +

    @@ -198,7 +272,7 @@ within box \( j \).

  • 13
  • 14
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html index 5b7eb2fcb..b08d98b67 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,21 +159,28 @@ MathJax.Hub.Config({ -

    A top-down approach, recursive binary splitting

    +

    Building a tree, regression

    -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 +There are mainly two steps -

    -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. +

      +
    1. 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 \).
    2. +
    3. 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 \).
    4. +
    + +How do we construct the regions \( R_1,\dots,R_J \)? +In theory, the regions could have any shape. However, we +choose to divide the predictor space into high-dimensional rectangles, +or boxes, for simplicity and for ease of interpretation of the +resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \) +that minimize the MSE, given by +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \).

    @@ -192,7 +203,7 @@ better tree in some future step.

  • 14
  • 15
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html index d42df5226..18420e466 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,49 +159,21 @@ MathJax.Hub.Config({ -

    Making a tree

    +

    A top-down approach, recursive binary splitting

    -In order to implement the recursive binary splitting we start by selecting -the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) -$$ -\left\{X\vert x_j < s\right\}, -$$ - -and -$$ -\left\{X\vert x_j \geq s\right\}, -$$ - -so that we obtain the lowest MSE, that is -$$ -\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, -$$ - -which we want to minimize by considering all predictors \( 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. +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

    -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 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.

    @@ -221,7 +197,7 @@ region contains more than five observations.

  • 15
  • 16
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html index 31a18c127..dbf71764d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -153,23 +157,51 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Pruning the tree

    +

    Making a 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. +In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +which we want to minimize by considering all predictors \( 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.

    -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 \). +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.

    @@ -194,7 +226,7 @@ parameter \( \alpha \).

  • 16
  • 17
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html index 3180d0399..2c4cf64af 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -153,35 +157,23 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Cost complexity pruning

    -For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that -$$ -\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, -$$ - -is as small as possible. Here \( \overline{T} \) is -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. +

    Pruning the tree

    -The tuning parameter \( \alpha \) controls a trade-off between the subtree’s -com- plexity 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. +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.

    -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 \). +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 \).

    @@ -207,7 +199,7 @@ subtree corresponding to \( \alpha \).

  • 17
  • 18
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html index 2b476d903..c39e03d2d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,29 +159,33 @@ MathJax.Hub.Config({ -

    Schematic Regression Procedure

    +

    Cost complexity pruning

    +For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +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.

    -

    -
    -

    - -

      -
    1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
    2. -
    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. -
    5. 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:
    6. - -
        -
      • 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.
      • -
      - -
    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. -
    -
    -
    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity 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 \).

    @@ -204,7 +212,7 @@ MathJax.Hub.Config({

  • 18
  • 19
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html index 6418b4ffe..c1b487279 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,21 +159,29 @@ MathJax.Hub.Config({ -

    A Classification Tree

    +

    Schematic Regression Procedure

    -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. +

    +
    +

    + +

      +
    1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
    2. +
    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. +
    5. 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:
    6. + +
        +
      • 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.
      • +
      + +
    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. +
    +
    +
    +

    @@ -197,7 +209,7 @@ fall into that region.

  • 19
  • 20
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html index 4d545ac98..ed8a2a46c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,26 +159,21 @@ MathJax.Hub.Config({ -

    Growing a classification tree

    +

    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. +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.

    @@ -202,7 +201,7 @@ than is the classification error rate.

  • 20
  • 21
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html index 6d018f0bb..e2a5685c5 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,46 +159,26 @@ MathJax.Hub.Config({ -

    Classification tree, how to split nodes

    +

    Growing a classification tree

    -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 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.

    -We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as -$$ -p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). -$$ - -

    -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 - -

    - -$$ -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}}. -$$ +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.

    @@ -222,7 +206,7 @@ $$

  • 21
  • 22
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html index 1b60813c2..6e3252297 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,10 +159,46 @@ MathJax.Hub.Config({ -

    Entropy and the ID3 algorithm

    +

    Classification tree, how to split nodes

    -More text and code to come here. +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 +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ + +

    +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 + +

    + +$$ +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}}. +$$

    @@ -186,7 +226,7 @@ More text and code to come here.

  • 22
  • 23
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html index fbf72f5b6..32319f7d4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,52 +159,39 @@ MathJax.Hub.Config({ -

    Cancer Data again now with Decision Trees

    +

    Entropy and the ID3 algorithm

    +

    +ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? - -

    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
    +
      +
    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. +
    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +
    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +
    7. Training examples are sorted to the appropriate descendant node.
    8. +
    9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
    10. +
    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    -# Load the data -cancer = load_breast_cancer() +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

    +We would like to select the attribute that is most useful for classifying +examples. + +

    +What is a good quantitative measure of the worth of an attribute? + +

    +Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

    +The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -print(X_train.shape) -print(X_test.shape) -# Logistic Regression -logreg = LogisticRegression(solver='lbfgs') -logreg.fit(X_train, y_train) -print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) -# Support vector machine -svm = SVC(gamma='auto', C=100) -svm.fit(X_train, y_train) -print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) -# Decision Trees -deep_tree_clf = DecisionTreeClassifier(max_depth=None) -deep_tree_clf.fit(X_train, y_train) -print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) -#now scale the data -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -# Logistic Regression -logreg.fit(X_train_scaled, y_train) -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) -# Support Vector Machine -svm.fit(X_train_scaled, y_train) -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) -# Decision Trees -deep_tree_clf.fit(X_train_scaled, y_train) -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) -

    @@ -227,7 +218,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)

  • 23
  • 24
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html index f67614dbf..6fbdf006c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,75 +159,11 @@ MathJax.Hub.Config({ -

    Another example, the moons again

    +

    Implementing the ID3 Algorithm

    +

    +more text to come here, material presented during lecture Friday Oct 25. - -

    from __future__ import division, print_function, unicode_literals
    -
    -# Common imports
    -import numpy as np
    -import os
    -
    -# to make this notebook's output stable across runs
    -np.random.seed(42)
    -
    -# To plot pretty figures
    -import matplotlib
    -import matplotlib.pyplot as plt
    -from matplotlib.colors import ListedColormap
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
    -
    -
    -from sklearn.svm import SVC
    -from sklearn import datasets
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.datasets import make_moons
    -from sklearn.tree import export_graphviz
    -
    -Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    -
    -deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    -deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    -deep_tree_clf1.fit(Xm, ym)
    -deep_tree_clf2.fit(Xm, ym)
    -
    -
    -def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    -    x1s = np.linspace(axes[0], axes[1], 100)
    -    x2s = np.linspace(axes[2], axes[3], 100)
    -    x1, x2 = np.meshgrid(x1s, x2s)
    -    X_new = np.c_[x1.ravel(), x2.ravel()]
    -    y_pred = clf.predict(X_new).reshape(x1.shape)
    -    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    -    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    -    if not iris:
    -        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    -        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    -    if plot_training:
    -        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
    -        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
    -        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
    -        plt.axis(axes)
    -    if iris:
    -        plt.xlabel("Petal length", fontsize=14)
    -        plt.ylabel("Petal width", fontsize=14)
    -    else:
    -        plt.xlabel(r"$x_1$", fontsize=18)
    -        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    -    if legend:
    -        plt.legend(loc="lower right", fontsize=14)
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    -plt.title("No restrictions", fontsize=16)
    -plt.subplot(122)
    -plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    -plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
    -plt.show()
    -

    @@ -250,7 +190,7 @@ plt.show()

  • 24
  • 25
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html index 3cb295cec..d2872aa0e 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,30 +159,51 @@ MathJax.Hub.Config({ -

    Playing around with regions

    +

    Cancer Data again now with Decision Trees

    -

    np.random.seed(6)
    -Xs = np.random.rand(100, 2) - 0.5
    -ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
     
    -angle = np.pi / 4
    -rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    -Xsr = Xs.dot(rotation_matrix)
    +# Load the data
    +cancer = load_breast_cancer()
     
    -tree_clf_s = DecisionTreeClassifier(random_state=42)
    -tree_clf_s.fit(Xs, ys)
    -tree_clf_sr = DecisionTreeClassifier(random_state=42)
    -tree_clf_sr.fit(Xsr, ys)
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -plt.subplot(122)
    -plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -
    -plt.show()
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
     

    @@ -206,7 +231,7 @@ plt.show()

  • 25
  • 26
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html index 52cfbfa50..b3376b407 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,24 +159,74 @@ MathJax.Hub.Config({ -

    Regression trees

    +

    Another example, the moons again

    -

    # Quadratic training set + noise
    +
    from __future__ import division, print_function, unicode_literals
    +
    +# Common imports
    +import numpy as np
    +import os
    +
    +# to make this notebook's output stable across runs
     np.random.seed(42)
    -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
    +# To plot pretty figures
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
     
    -tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
    -tree_reg.fit(X, y)
    +
    +from sklearn.svm import SVC
    +from sklearn import datasets
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.datasets import make_moons
    +from sklearn.tree import export_graphviz
    +
    +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    +
    +deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    +deep_tree_clf1.fit(Xm, ym)
    +deep_tree_clf2.fit(Xm, ym)
    +
    +
    +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if not iris:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    if plot_training:
    +        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
    +        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
    +        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
    +        plt.axis(axes)
    +    if iris:
    +        plt.xlabel("Petal length", fontsize=14)
    +        plt.ylabel("Petal width", fontsize=14)
    +    else:
    +        plt.xlabel(r"$x_1$", fontsize=18)
    +        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +    if legend:
    +        plt.legend(loc="lower right", fontsize=14)
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("No restrictions", fontsize=16)
    +plt.subplot(122)
    +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
    +plt.show()
     

    @@ -200,7 +254,7 @@ tree_reg.fit(X, y)

  • 26
  • 27
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html index 4a152e67f..3f1a352e8 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,78 +159,28 @@ MathJax.Hub.Config({ -

    Final regressor code

    +

    Playing around with regions

    -

    from sklearn.tree import DecisionTreeRegressor
    +
    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
     
    -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)
    +angle = np.pi / 4
    +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    +Xsr = Xs.dot(rotation_matrix)
     
    -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}$")
    +tree_clf_s = DecisionTreeClassifier(random_state=42)
    +tree_clf_s.fit(Xs, ys)
    +tree_clf_sr = DecisionTreeClassifier(random_state=42)
    +tree_clf_sr.fit(Xsr, ys)
     
     plt.figure(figsize=(11, 4))
     plt.subplot(121)
    -plot_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)
    -
    +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
     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)
    +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
     
     plt.show()
     
    @@ -256,7 +210,7 @@ plt.show()
  • 27
  • 28
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html index 02d40e42e..1abf03cbe 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,18 +159,26 @@ MathJax.Hub.Config({ -

    Pros and cons of trees, pros

    +

    Regression trees

    +

    -

      -
    • 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)
    • -
    + +
    # 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)
    +
    +

      @@ -191,6 +203,8 @@ MathJax.Hub.Config({
    • 27
    • 28
    • 29
    • +
    • ...
    • +
    • 31
    • »
    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html index 9bcb742f8..261df3269 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,20 +159,81 @@ MathJax.Hub.Config({ -

    Disadvantages

    +

    Final regressor code

    +

    -

      -
    • 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
    • -
    + +
    from sklearn.tree import DecisionTreeRegressor
     
    -However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
    +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()
    +

    @@ -193,6 +258,9 @@ However, by aggregating many decision trees, using methods like bagging, random

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • ...
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html index 6598f41eb..ebac943c4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,47 +159,18 @@ MathJax.Hub.Config({ -

    Bagging

    +

    Pros and cons of trees, pros

    -

    -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. +

      +
    • 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)
    • +
    -

    -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. - -

      @@ -218,6 +193,8 @@ predictor, averaged over all \( B \) trees.
    • 27
    • 28
    • 29
    • +
    • 30
    • +
    • 31
    • »
    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html index 2660af6af..c3e65aa61 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,23 +159,20 @@ MathJax.Hub.Config({ -

    Simple example, head or tail

    -

    +

    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. - -
    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])
    -plt.show()
    -

    @@ -194,6 +195,8 @@ plt.show()

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html index d32ea35dd..ed701c94f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,44 +159,45 @@ MathJax.Hub.Config({ -

    Random forests

    +

    Bagging

    -Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. +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.

    -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. +Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method.

    -A fresh sample of \( m \) predictors is -taken at each split, and typically we choose -$$ -m\approx \sqrt{p}. -$$ - -In building a random forest, at -each split in the tree, the algorithm is not even allowed to consider -a majority of the available predictors. +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.

    -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 -quanti- ties. In particular, this means that bagging will not lead to -a substantial reduction in variance over a single tree in this -setting. +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.

    @@ -215,6 +220,8 @@ setting.

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html index 8080d2514..094e5e5c5 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,20 +159,22 @@ MathJax.Hub.Config({ -

    A simple scikit-learn example

    +

    Simple example, head or tail

    -

    from sklearn.ensemble import RandomForestClassifier
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -# Data set not specificied
    -X = dataset.XXX
    -Y = dataset.YYY
    -#Instantiate the model with 100 trees and entropy as splitting criteria
    -Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
    -#Cross validation
    -accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
    +
    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])
    +plt.show()
     

    @@ -190,6 +196,8 @@ accuracy = cross_validate(Random_Forest_mode

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html index d64c09e5b..a41f45ab6 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,61 +159,45 @@ MathJax.Hub.Config({ -

    Please, not the moons again!

    +

    Random forests

    +

    +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. - -

    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)
    -

    +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. - -

    from sklearn.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))
    -

    +A fresh sample of \( m \) predictors is +taken at each split, and typically we choose +$$ +m\approx \sqrt{p}. +$$ - -

    log_clf = LogisticRegression(random_state=42)
    -rnd_clf = RandomForestClassifier(random_state=42)
    -svm_clf = SVC(probability=True, random_state=42)
    +In building a random forest, at
    +each split in the tree, the algorithm is not even allowed to consider
    +a majority of the available predictors.
     
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='soft')
    -voting_clf.fit(X_train, y_train)
    -

    +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 +quanti- ties. In particular, this means that bagging will not lead to +a substantial reduction in variance over a single tree in this +setting. - -

    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))
    -

    @@ -229,6 +217,8 @@ voting_clf.fit(X_train, y_train)

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html index 4ee762999..2371b947f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,63 +159,20 @@ MathJax.Hub.Config({ -

    Bagging examples

    - +

    A simple scikit-learn example

    -

    from sklearn.ensemble import BaggingClassifier
    -from sklearn.tree import DecisionTreeClassifier
    -
    -bag_clf = BaggingClassifier(
    -    DecisionTreeClassifier(random_state=42), n_estimators=500,
    -    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    -bag_clf.fit(X_train, y_train)
    -y_pred = bag_clf.predict(X_test)
    -
    -

    - - -

    from sklearn.metrics import accuracy_score
    -print(accuracy_score(y_test, y_pred))
    -
    -

    - - -

    tree_clf = DecisionTreeClassifier(random_state=42)
    -tree_clf.fit(X_train, y_train)
    -y_pred_tree = tree_clf.predict(X_test)
    -print(accuracy_score(y_test, y_pred_tree))
    -
    -

    - - -

    from matplotlib.colors import ListedColormap
    -
    -def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    -    x1s = np.linspace(axes[0], axes[1], 100)
    -    x2s = np.linspace(axes[2], axes[3], 100)
    -    x1, x2 = np.meshgrid(x1s, x2s)
    -    X_new = np.c_[x1.ravel(), x2.ravel()]
    -    y_pred = clf.predict(X_new).reshape(x1.shape)
    -    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    -    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    -    if contour:
    -        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    -        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    -    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    -    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    -    plt.axis(axes)
    -    plt.xlabel(r"$x_1$", fontsize=18)
    -    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    -plt.figure(figsize=(11,4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf, X, y)
    -plt.title("Decision Tree", fontsize=14)
    -plt.subplot(122)
    -plot_decision_boundary(bag_clf, X, y)
    -plt.title("Decision Trees with Bagging", fontsize=14)
    -plt.show()
    +
    from sklearn.ensemble import RandomForestClassifier
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +# Data set not specificied
    +X = dataset.XXX
    +Y = dataset.YYY
    +#Instantiate the model with 100 trees and entropy as splitting criteria
    +Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
    +#Cross validation
    +accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
     

    @@ -231,6 +192,8 @@ plt.show()

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html index 154f3758c..7fd7f2ec4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,24 +159,60 @@ MathJax.Hub.Config({ -

    Then random forests

    +

    Please, not the moons again!

    -

    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)
    +
    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)
     

    -

    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) 
    +
    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))
     

    @@ -191,6 +231,8 @@ np.sum(y_pred =

  • 27
  • 28
  • 29
  • +
  • 30
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html index 0988bec6c..935838dd3 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -153,13 +157,67 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Boosting and more

    -More material to come here. +

    Bagging examples

    + +

    from sklearn.ensemble import BaggingClassifier
    +from sklearn.tree import DecisionTreeClassifier
    +
    +bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(random_state=42), n_estimators=500,
    +    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    +bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +
    +

    + + +

    from sklearn.metrics import accuracy_score
    +print(accuracy_score(y_test, y_pred))
    +
    +

    + + +

    tree_clf = DecisionTreeClassifier(random_state=42)
    +tree_clf.fit(X_train, y_train)
    +y_pred_tree = tree_clf.predict(X_test)
    +print(accuracy_score(y_test, y_pred_tree))
    +
    +

    + + +

    from matplotlib.colors import ListedColormap
    +
    +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if contour:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    +    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    +    plt.axis(axes)
    +    plt.xlabel(r"$x_1$", fontsize=18)
    +    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +plt.figure(figsize=(11,4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf, X, y)
    +plt.title("Decision Tree", fontsize=14)
    +plt.subplot(122)
    +plot_decision_boundary(bag_clf, X, y)
    +plt.title("Decision Trees with Bagging", fontsize=14)
    +plt.show()
    +
    +

      @@ -175,6 +233,9 @@ More material to come here.
    • 27
    • 28
    • 29
    • +
    • 30
    • +
    • 31
    • +
    • »
    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html index b2684c0b1..861de541c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html @@ -42,40 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -114,34 +115,35 @@ MathJax.Hub.Config({ Contents @@ -155,13 +157,28 @@ MathJax.Hub.Config({

     

     

     

    - - -

    Boosting and more

    -More material to come here. + +

    Then 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) 
    +
    +

      @@ -177,6 +194,8 @@ More material to come here.
    • 28
    • 29
    • 30
    • +
    • 31
    • +
    • »
    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html index c4795b4f2..99821f748 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html @@ -42,9 +42,9 @@ Automatically generated HTML file from DocOnce source
  • Decision trees, overarching aims
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Maxwell-Boltzmann velocity distribution
  • +
  • General Features
  • +
  • How do we set it up?
  • +
  • Decision trees and Regression
  • Building a tree, regression
  • A top-down approach, recursive binary splitting
  • Making a tree
  • Pruning the tree
  • Cost complexity pruning
  • -
  • A schematic procedure
  • -
  • A classification tree
  • +
  • Schematic Regression Procedure
  • +
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • Entropy and the ID3 algorithm
  • -
  • Writing your own code for a classification tree
  • -
  • Back to moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Classification again: The zoo data
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • Pros and cons of trees, pros
  • Disadvantages
  • Bagging
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html index a1f2bc91d..60b829003 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html @@ -42,39 +42,41 @@ Automatically generated HTML file from DocOnce source @@ -113,33 +115,35 @@ MathJax.Hub.Config({ Contents @@ -198,7 +202,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 29
  • +
  • 31
  • »
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html index 791a5279f..7cf28ce07 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html @@ -193,7 +193,26 @@ and leaf nodes which are then connected by branches.
    -

    How do we set it up?

    +

    General Features

    + +

    +Decision trees classify instances by sorting top down. + +

      +

    • A leaf provides the classification of the instance.
    • +

    • A node specifies a test of some attribute of the instance.
    • +

    • A branch corresponds to a possible values an attribute.
    • +

    • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
    • +
    +

    + +This processis then repeated for the subtree rooted at the new +node. +

    + + +
    +

    How do we set it up?

    In simplified terms, the process of training a decision tree and @@ -212,7 +231,7 @@ Then we are essentially done!

    -

    Decision trees and Regression

    +

    Decision trees and Regression

    @@ -309,7 +328,7 @@ plt.show()

    -

    Building a tree, regression

    +

    Building a tree, regression

    There are mainly two steps @@ -339,7 +358,7 @@ within box \( j \).

    -

    A top-down approach, recursive binary splitting

    +

    A top-down approach, recursive binary splitting

    Unfortunately, it is computationally infeasible to consider every @@ -358,7 +377,7 @@ better tree in some future step.

    -

    Making a tree

    +

    Making a tree

    In order to implement the recursive binary splitting we start by selecting @@ -411,7 +430,7 @@ region contains more than five observations.

    -

    Pruning the tree

    +

    Pruning the tree

    The above procedure is rather straightforward, but leads often to @@ -430,7 +449,7 @@ parameter \( \alpha \).

    -

    Cost complexity pruning

    +

    Cost complexity pruning

    For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that

     
    $$ @@ -463,7 +482,7 @@ subtree corresponding to \( \alpha \).

    -

    Schematic Regression Procedure

    +

    Schematic Regression Procedure

    @@ -488,7 +507,7 @@ subtree corresponding to \( \alpha \).
    -

    A Classification Tree

    +

    A Classification Tree

    A classification tree is very similar to a regression tree, except @@ -507,7 +526,7 @@ fall into that region.

    -

    Growing a classification tree

    +

    Growing a classification tree

    The task of growing a @@ -531,7 +550,7 @@ than is the classification error rate.

    -

    Classification tree, how to split nodes

    +

    Classification tree, how to split nodes

    If our targets are the outcome of a classification process that takes for example @@ -580,15 +599,52 @@ $$

    -

    Entropy and the ID3 algorithm

    +

    Entropy and the ID3 algorithm

    -More text and code to come here. +ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

      +

    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. +

    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +

    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +

    7. Training examples are sorted to the appropriate descendant node.
    8. +

    9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
    10. +

    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    +

    + +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

    +We would like to select the attribute that is most useful for classifying +examples. + +

    +What is a good quantitative measure of the worth of an attribute? + +

    +Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

    +The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree.

    -

    Cancer Data again now with Decision Trees

    +

    Implementing the ID3 Algorithm

    + +

    +more text to come here, material presented during lecture Friday Oct 25. +

    + + +
    +

    Cancer Data again now with Decision Trees

    @@ -638,7 +694,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)

    -

    Another example, the moons again

    +

    Another example, the moons again

    @@ -711,7 +767,7 @@ plt.show()

    -

    Playing around with regions

    +

    Playing around with regions

    @@ -740,7 +796,7 @@ plt.show()

    -

    Regression trees

    +

    Regression trees

    @@ -763,7 +819,7 @@ tree_reg.fit(X, y)

    -

    Final regressor code

    +

    Final regressor code

    @@ -842,7 +898,7 @@ plt.show()

    -

    Pros and cons of trees, pros

    +

    Pros and cons of trees, pros