# Program to test the Metropolis algorithm with one particle at given temp in
-# one dimension
-#!/usr/bin/env python
-importnumpyasnp
-importmatplotlib.mlabasmlab
-importmatplotlib.pyplotasplt
-importrandom
-frommathimport sqrt, exp, log
-fromsklearn.preprocessingimport PolynomialFeatures
-fromsklearn.linear_modelimport LinearRegression
-# initialize the rng with a seed
-random.seed()
-# Hard coding of input parameters
-MCcycles =100000
-Temperature =2.0
-beta =1./Temperature
-InitialVelocity =-2.0
-CurrentVelocity = InitialVelocity
-Energy =0.5*InitialVelocity*InitialVelocity
-VelocityRange =10*sqrt(Temperature)
-VelocityStep =2*VelocityRange/10.
-AverageEnergy = Energy
-AverageEnergy2 = Energy*Energy
-VelocityValues = np.zeros(MCcycles)
-# The Monte Carlo sampling with Metropolis starts here
-for i inrange (1, MCcycles, 1):
- TrialVelocity = CurrentVelocity + (2.0*random.random() -1.0)*VelocityStep
- EnergyChange =0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);
- if random.random() <= exp(-beta*EnergyChange):
- CurrentVelocity = TrialVelocity
- Energy += EnergyChange
- VelocityValues[i] = CurrentVelocity
- AverageEnergy += Energy
- AverageEnergy2 += Energy*Energy
-#Final averages
-AverageEnergy = AverageEnergy/MCcycles
-AverageEnergy2 = AverageEnergy2/MCcycles
-Variance = AverageEnergy2 - AverageEnergy*AverageEnergy
-print(AverageEnergy, Variance)
-n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')
+
+
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \)
+
-plt.xlabel('$v$')
-plt.ylabel('Velocity distribution P(v)')
-plt.title(r'Velocity histogram at $k_BT=2$')
-plt.axis([-5, 5, 0, 600])
-plt.grid(True)
-fromcollectionsimport Counter
+distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
-#print (Counter(VelocityValues))
+
+
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 \).
+
-print (VelocityValues[:20])
-VelocityValues=list(Counter(VelocityValues).keys())
-d=list(Counter(VelocityValues).values())
+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 predic- tive 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,
+$$
-VelocityValues=np.asarray(VelocityValues)[:, np.newaxis]
-d=np.asarray(d)
-print (VelocityValues.shape, d.shape)
+where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within the $j$th
+box.
-plt.scatter(VelocityValues, d)
-plt.show()
-
-#2nd Degree Polynomial
-poly_feat=PolynomialFeatures(degree=20, include_bias=False)
-X_poly=poly_feat.fit_transform(VelocityValues)
-lin_reg=LinearRegression()
-poly_fit=lin_reg.fit(X_poly,d)
-
-y_plot=poly_fit.predict(X_poly)
-plt.title("Polynomial Fit")
-plt.plot(VelocityValues, y_plot, color='black', label="Fit")
-plt.show()
-
-#Decision Trees
-
-fromsklearn.treeimport DecisionTreeRegressor
-regr_1=DecisionTreeRegressor(max_depth=2)
-regr_2=DecisionTreeRegressor(max_depth=5)
-regr_3=DecisionTreeRegressor(max_depth=7)
-regr_1.fit(VelocityValues, d)
-regr_2.fit(VelocityValues, d)
-regr_3.fit(VelocityValues, d)
-
-X_test = np.arange(0.0, MCcycles, 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)
-
-plt.title("Decision Tree")
-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.show()
-
-There are mainly two steps
+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
-
-
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \)
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
-
-
-How do we construct the regions \( R_1,\dots,R_J \)?
-In theory, the 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 predic- tive 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 the $j$th
-box.
+
+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.
-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
+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 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.
+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.
@@ -197,7 +223,7 @@ better tree in some future step.
-In order to implement the recursive binary splitting we start by selecting
-the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
-$$
-\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 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.
-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 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 \).
@@ -226,7 +196,7 @@ region contains more than five observations.
+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.
-The above procedure is rather straightforward, but leads often to
-overfitting and unnecessarily large and complicated trees. The basic
-idea is to grow a large tree \( T_0 \) and then prune it back in order to
-obtain a subtree. A smaller tree with fewer splits (fewer regions) can
-lead to smaller variance and better interpretation at the cost of a
-little more bias.
+The 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 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 \).
+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 \).
-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.
+
A schematic procedure
-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.
+
+
+
+
+
+
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
+
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
+
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
+
+
+
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
+
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
+
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
+
+
+
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
+
+
+
-
-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 \).
@@ -212,7 +206,7 @@ subtree corresponding to \( \alpha \).
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
-
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
-
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
-
-
-
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
-
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
-
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
-
-
-
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
-
-
-
-
+A classification tree 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.
-A classification tree is very similar to a regression tree, except
-that it is used to predict a qualitative response rather than a
-quantitative one. Recall that for a regression tree, the predicted
-response for an observation is given by the mean response of the
-training observations that belong to the same terminal node. In
-contrast, for a classification tree, we predict that each observation
-belongs to the most commonly occurring class of training observations
-in the region to which it belongs. In interpreting the results of a
-classification tree, we are often interested not only in the class
-prediction corresponding to a particular terminal node region, but
-also in the class proportions among the training observations that
-fall into that region.
+The task of growing a
+classification tree is quite similar to the task of growing a
+regression tree. Just as in the regression setting, we use recursive
+binary splitting to grow a classification tree. However, in the
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+error rate. Since we plan to assign an observation in a given region
+to the most commonly occurring error rate class of training
+observations in that region, the classification error rate is simply
+the fraction of the training observations in that region that do not
+belong to the most common class.
+
+
+When building a classification tree, either the Gini index or the
+entropy are typically used to evaluate the quality of a particular
+split, since these two approaches are more sensitive to node purity
+than is the classification error rate.
+If our targets are the outcome of a classification process that takes for example
+\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
-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).
+$$
-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.
+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
+
+
-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.
+
Entropy and the ID3 algorithm
-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
-
-
defentropy(target_col):
+ """
+ Calculate the entropy of a dataset.
+ The only parameter of this function is the target_col parameter which specifies the target column
+ """
+ elements,counts = np.unique(target_col,return_counts =True)
+ entropy = np.sum([(-counts[i]/np.sum(counts))*np.log2(counts[i]/np.sum(counts)) for i inrange(len(elements))])
+ return entropy
+
+defInfoGain(data,split_attribute_name,target_name="class"):
+ """
+ Calculate the information gain of a dataset. This function takes three parameters:
+ 1. data = The dataset for whose feature the IG should be calculated
+ 2. split_attribute_name = the name of the feature for which the information gain should be calculated
+ 3. target_name = the name of the target feature. The default for this example is "class"
+ """
+ #Calculate the entropy of the total dataset
+ total_entropy = entropy(data[target_name])
+
+ ##Calculate the entropy of the dataset
+
+ #Calculate the values and the corresponding counts for the split attribute
+ vals,counts= np.unique(data[split_attribute_name],return_counts=True)
+
+ #Calculate the weighted entropy
+ Weighted_Entropy = np.sum([(counts[i]/np.sum(counts))*entropy(data.where(data[split_attribute_name]==vals[i]).dropna()[target_name]) for i inrange(len(vals))])
+
+ #Calculate the information gain
+ Information_Gain = total_entropy - Weighted_Entropy
+ return Information_Gain
+
+
+defID3(data,originaldata,features,target_attribute_name="class",parent_node_class =None):
+ #Define the stopping criteria --> If one of this is satisfied, we want to return a leaf node#
+
+ #If all target_values have the same value, return this value
+ iflen(np.unique(data[target_attribute_name])) <=1:
+ return np.unique(data[target_attribute_name])[0]
+
+ #If the dataset is empty, return the mode target feature value in the original dataset
+ eliflen(data)==0:
+ return np.unique(originaldata[target_attribute_name])[np.argmax(np.unique(originaldata[target_attribute_name],return_counts=True)[1])]
+
+ #If the feature space is empty, return the mode target feature value of the direct parent node --> Note that
+ #the direct parent node is that node which has called the current run of the ID3 algorithm and hence
+ #the mode target feature value is stored in the parent_node_class variable.
+
+ eliflen(features) ==0:
+ return parent_node_class
+
+ #If none of the above holds true, grow the tree!
+
+ else:
+ #Set the default value for this node --> The mode target feature value of the current node
+ parent_node_class = np.unique(data[target_attribute_name])[np.argmax(np.unique(data[target_attribute_name],return_counts=True)[1])]
+
+ #Select the feature which best splits the dataset
+ item_values = [InfoGain(data,feature,target_attribute_name) for feature in features] #Return the information gain values for the features in the dataset
+ best_feature_index = np.argmax(item_values)
+ best_feature = features[best_feature_index]
+
+ #Create the tree structure. The root gets the name of the feature (best_feature) with the maximum information
+ #gain in the first run
+ tree = {best_feature:{}}
+
+
+ #Remove the feature with the best inforamtion gain from the feature space
+ features = [i for i in features if i != best_feature]
+
+ #Grow a branch under the root node for each possible value of the root node feature
+
+ for value in np.unique(data[best_feature]):
+ value = value
+ #Split the dataset along the value of the feature with the largest information gain and therwith create sub_datasets
+ sub_data = data.where(data[best_feature] == value).dropna()
+
+ #Call the ID3 algorithm for each of those sub_datasets with the new parameters --> Here the recursion comes in!
+ subtree = ID3(sub_data,dataset,features,target_attribute_name,parent_node_class)
+
+ #Add the sub tree, grown from the sub_dataset to the tree under the root node
+ tree[best_feature][value] = subtree
+
+ return(tree)
+
defentropy(target_col):
- """
- Calculate the entropy of a dataset.
- The only parameter of this function is the target_col parameter which specifies the target column
- """
- elements,counts = np.unique(target_col,return_counts =True)
- entropy = np.sum([(-counts[i]/np.sum(counts))*np.log2(counts[i]/np.sum(counts)) for i inrange(len(elements))])
- return entropy
+
from__future__import division, print_function, unicode_literals
-defInfoGain(data,split_attribute_name,target_name="class"):
- """
- Calculate the information gain of a dataset. This function takes three parameters:
- 1. data = The dataset for whose feature the IG should be calculated
- 2. split_attribute_name = the name of the feature for which the information gain should be calculated
- 3. target_name = the name of the target feature. The default for this example is "class"
- """
- #Calculate the entropy of the total dataset
- total_entropy = entropy(data[target_name])
-
- ##Calculate the entropy of the dataset
-
- #Calculate the values and the corresponding counts for the split attribute
- vals,counts= np.unique(data[split_attribute_name],return_counts=True)
-
- #Calculate the weighted entropy
- Weighted_Entropy = np.sum([(counts[i]/np.sum(counts))*entropy(data.where(data[split_attribute_name]==vals[i]).dropna()[target_name]) for i inrange(len(vals))])
-
- #Calculate the information gain
- Information_Gain = total_entropy - Weighted_Entropy
- return Information_Gain
-
+# Common imports
+importnumpyasnp
+importos
-defID3(data,originaldata,features,target_attribute_name="class",parent_node_class =None):
- #Define the stopping criteria --> If one of this is satisfied, we want to return a leaf node#
-
- #If all target_values have the same value, return this value
- iflen(np.unique(data[target_attribute_name])) <=1:
- return np.unique(data[target_attribute_name])[0]
-
- #If the dataset is empty, return the mode target feature value in the original dataset
- eliflen(data)==0:
- return np.unique(originaldata[target_attribute_name])[np.argmax(np.unique(originaldata[target_attribute_name],return_counts=True)[1])]
-
- #If the feature space is empty, return the mode target feature value of the direct parent node --> Note that
- #the direct parent node is that node which has called the current run of the ID3 algorithm and hence
- #the mode target feature value is stored in the parent_node_class variable.
-
- eliflen(features) ==0:
- return parent_node_class
-
- #If none of the above holds true, grow the tree!
-
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+importmatplotlib
+importmatplotlib.pyplotasplt
+frommatplotlib.colorsimport ListedColormap
+plt.rcParams['axes.labelsize'] =14
+plt.rcParams['xtick.labelsize'] =12
+plt.rcParams['ytick.labelsize'] =12
+
+
+fromsklearn.svmimport SVC
+fromsklearnimport datasets
+fromsklearn.treeimport DecisionTreeClassifier
+fromsklearn.datasetsimport make_moons
+fromsklearn.treeimport 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)
+
+
+defplot_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)
+ ifnot 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:
- #Set the default value for this node --> The mode target feature value of the current node
- parent_node_class = np.unique(data[target_attribute_name])[np.argmax(np.unique(data[target_attribute_name],return_counts=True)[1])]
-
- #Select the feature which best splits the dataset
- item_values = [InfoGain(data,feature,target_attribute_name) for feature in features] #Return the information gain values for the features in the dataset
- best_feature_index = np.argmax(item_values)
- best_feature = features[best_feature_index]
-
- #Create the tree structure. The root gets the name of the feature (best_feature) with the maximum information
- #gain in the first run
- tree = {best_feature:{}}
-
-
- #Remove the feature with the best inforamtion gain from the feature space
- features = [i for i in features if i != best_feature]
-
- #Grow a branch under the root node for each possible value of the root node feature
-
- for value in np.unique(data[best_feature]):
- value = value
- #Split the dataset along the value of the feature with the largest information gain and therwith create sub_datasets
- sub_data = data.where(data[best_feature] == value).dropna()
-
- #Call the ID3 algorithm for each of those sub_datasets with the new parameters --> Here the recursion comes in!
- subtree = ID3(sub_data,dataset,features,target_attribute_name,parent_node_class)
-
- #Add the sub tree, grown from the sub_dataset to the tree under the root node
- tree[best_feature][value] = subtree
-
- return(tree)
+ 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()
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()
+#Import the dataset
+dataset = pd.read_csv('data/zoo.csv')
+#We drop the animal names since this is not a good feature to split the data on
+#dataset=dataset.drop('animal_name',axis=1)
+#Split the data into a training and a testing set
+train_features = dataset.iloc[:80,:-1]
+test_features = dataset.iloc[80:,:-1]
+train_targets = dataset.iloc[:80,-1]
+test_targets = dataset.iloc[80:,-1]
+#Train the model
+tree = DecisionTreeClassifier(criterion ='entropy').fit(train_features,train_targets)
+#Predict the classes of new, unseen data
+prediction = tree.predict(test_features)
+#Check the accuracy
+print("The prediction accuracy is: ",tree.score(test_features,test_targets)*100,"%")
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)
+
-#Import the dataset
-dataset = pd.read_csv('data/zoo.csv')
-#We drop the animal names since this is not a good feature to split the data on
-#dataset=dataset.drop('animal_name',axis=1)
-#Split the data into a training and a testing set
-train_features = dataset.iloc[:80,:-1]
-test_features = dataset.iloc[80:,:-1]
-train_targets = dataset.iloc[:80,-1]
-test_targets = dataset.iloc[80:,-1]
-#Train the model
-tree = DecisionTreeClassifier(criterion ='entropy').fit(train_features,train_targets)
-#Predict the classes of new, unseen data
-prediction = tree.predict(test_features)
-#Check the accuracy
-print("The prediction accuracy is: ",tree.score(test_features,test_targets)*100,"%")
-
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)
+
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.
+
+
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
-
+
+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.
-However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+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.
@@ -196,7 +220,6 @@ However, by aggregating many decision trees, using methods like bagging, random
-The plain decision trees suffer from high
-variance. This means that if we split the training data into two parts
-at random, and fit a decision tree to both halves, the results that we
-get could be quite different. In contrast, a procedure with low
-variance will yield similar results if applied repeatedly to distinct
-data sets; linear regression tends to have low variance, if the ratio
-of \( n \) to \( p \) is moderately large.
-
-
-Bootstrap aggregation, or just bagging, is a
-general-purpose procedure for reducing the variance of a statistical
-learning method.
-
-
-Bagging typically results in improved accuracy
-over prediction using a single tree. Unfortunately, however, it can be
-difficult to interpret the resulting model. Recall that one of the
-advantages of decision trees is the attractive and easily interpreted
-diagram that results.
-
-
-However, when we bag a large number of trees, it is no longer
-possible to represent the resulting statistical learning procedure
-using a single tree, and it is no longer clear which variables are
-most important to the procedure. Thus, bagging improves prediction
-accuracy at the expense of interpretability. Although the collection
-of bagged trees is much more difficult to interpret than a single
-tree, one can obtain an overall summary of the importance of each
-predictor using the MSE (for bagging regression trees) or the Gini
-index (for bagging classification trees). In the case of bagging
-regression trees, we can record the total amount that the MSE is
-decreased due to splits over a given predictor, averaged over all \( B \) possible
-trees. A large value indicates an important predictor. Similarly, in
-the context of bagging classification trees, we can add up the total
-amount that the Gini index is decreased by splits over a given
-predictor, averaged over all \( B \) trees.
+
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
+
+
+A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
+$$
+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.
+
+
+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.
-
-
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
-
-
-As in bagging, we build a
-number of decision trees on bootstrapped training samples. But when
-building these decision trees, each time a split in a tree is
-considered, a random sample of \( m \) predictors is chosen as split
-candidates from the full set of \( p \) predictors. The split is allowed to
-use only one of those \( m \) predictors.
-
-
-A fresh sample of \( m \) predictors is
-taken at each split, and typically we choose
-$$
-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.
-
-
-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.
+
+
fromsklearn.ensembleimport RandomForestClassifier
+fromsklearn.preprocessingimport LabelEncoder
+fromsklearn.model_selectionimport 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']
+
fromsklearn.ensembleimport RandomForestClassifier
-fromsklearn.preprocessingimport LabelEncoder
-fromsklearn.model_selectionimport 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']
+
A classification tree is very similar to a regression tree, except
@@ -615,7 +513,7 @@ fall into that region.
-
Growing a classification tree
+
Growing a classification tree
The task of growing a
@@ -639,7 +537,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
\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
@@ -686,12 +584,15 @@ $$
-
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)
More material to come here.
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
index 996c64b27..47508df7b 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
@@ -64,39 +64,38 @@ div { text-align: justify; text-justify: inter-word; }
'sections': [('Decision trees, overarching aims', 2, None, '___sec0'),
('How do we set it up?', 2, None, '___sec1'),
('Decision trees and Regression', 2, None, '___sec2'),
- ('Maxwell-Boltzmann velocity distribution', 2, None, '___sec3'),
- ('Building a tree, regression', 2, None, '___sec4'),
+ ('Building a tree, regression', 2, None, '___sec3'),
('A top-down approach, recursive binary splitting',
2,
None,
- '___sec5'),
- ('Making a tree', 2, None, '___sec6'),
- ('Pruning the tree', 2, None, '___sec7'),
- ('Cost complexity pruning', 2, None, '___sec8'),
- ('A schematic procedure', 2, None, '___sec9'),
- ('A classification tree', 2, None, '___sec10'),
- ('Growing a classification tree', 2, None, '___sec11'),
- ('Classification tree, how to split nodes', 2, None, '___sec12'),
- ('Entropy and the ID3 algorithm', 2, None, '___sec13'),
+ '___sec4'),
+ ('Making a tree', 2, None, '___sec5'),
+ ('Pruning the tree', 2, None, '___sec6'),
+ ('Cost complexity pruning', 2, None, '___sec7'),
+ ('A schematic procedure', 2, None, '___sec8'),
+ ('A classification tree', 2, None, '___sec9'),
+ ('Growing a classification tree', 2, None, '___sec10'),
+ ('Classification tree, how to split nodes', 2, None, '___sec11'),
+ ('Entropy and the ID3 algorithm', 2, None, '___sec12'),
('Writing your own code for a classification tree',
2,
None,
- '___sec14'),
- ('Back to moons again', 2, None, '___sec15'),
- ('Playing around with regions', 2, None, '___sec16'),
- ('Regression trees', 2, None, '___sec17'),
- ('Final regressor code', 2, None, '___sec18'),
- ('Classification again: The zoo data', 2, None, '___sec19'),
- ('Pros and cons of trees, pros', 2, None, '___sec20'),
- ('Disadvantages', 2, None, '___sec21'),
- ('Bagging', 2, None, '___sec22'),
- ('Simple example, head or tail', 2, None, '___sec23'),
- ('Random forests', 2, None, '___sec24'),
- ('A simple scikit-learn example', 2, None, '___sec25'),
- ('Please, not the moons again!', 2, None, '___sec26'),
- ('Bagging examples', 2, None, '___sec27'),
- ('Then random forests', 2, None, '___sec28'),
- ('Boosting and more', 2, None, '___sec29')]}
+ '___sec13'),
+ ('Back to moons again', 2, None, '___sec14'),
+ ('Playing around with regions', 2, None, '___sec15'),
+ ('Regression trees', 2, None, '___sec16'),
+ ('Final regressor code', 2, None, '___sec17'),
+ ('Classification again: The zoo data', 2, None, '___sec18'),
+ ('Pros and cons of trees, pros', 2, None, '___sec19'),
+ ('Disadvantages', 2, None, '___sec20'),
+ ('Bagging', 2, None, '___sec21'),
+ ('Simple example, head or tail', 2, None, '___sec22'),
+ ('Random forests', 2, None, '___sec23'),
+ ('A simple scikit-learn example', 2, None, '___sec24'),
+ ('Please, not the moons again!', 2, None, '___sec25'),
+ ('Bagging examples', 2, None, '___sec26'),
+ ('Then random forests', 2, None, '___sec27'),
+ ('Boosting and more', 2, None, '___sec28')]}
end of tocinfo -->
@@ -138,7 +137,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Dec 17, 2018
+
Oct 24, 2019
@@ -291,108 +290,7 @@ plt.show()
-
Maxwell-Boltzmann velocity distribution
-
-
-
-
-
# Program to test the Metropolis algorithm with one particle at given temp in
-# one dimension
-#!/usr/bin/env python
-importnumpyasnp
-importmatplotlib.mlabasmlab
-importmatplotlib.pyplotasplt
-importrandom
-frommathimport sqrt, exp, log
-fromsklearn.preprocessingimport PolynomialFeatures
-fromsklearn.linear_modelimport LinearRegression
-# initialize the rng with a seed
-random.seed()
-# Hard coding of input parameters
-MCcycles = 100000
-Temperature = 2.0
-beta = 1./Temperature
-InitialVelocity = -2.0
-CurrentVelocity = InitialVelocity
-Energy = 0.5*InitialVelocity*InitialVelocity
-VelocityRange = 10*sqrt(Temperature)
-VelocityStep = 2*VelocityRange/10.
-AverageEnergy = Energy
-AverageEnergy2 = Energy*Energy
-VelocityValues = np.zeros(MCcycles)
-# The Monte Carlo sampling with Metropolis starts here
-for i inrange (1, MCcycles, 1):
- TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep
- EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);
- if random.random() <= exp(-beta*EnergyChange):
- CurrentVelocity = TrialVelocity
- Energy += EnergyChange
- VelocityValues[i] = CurrentVelocity
- AverageEnergy += Energy
- AverageEnergy2 += Energy*Energy
-#Final averages
-AverageEnergy = AverageEnergy/MCcycles
-AverageEnergy2 = AverageEnergy2/MCcycles
-Variance = AverageEnergy2 - AverageEnergy*AverageEnergy
-print(AverageEnergy, Variance)
-n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')
-
-plt.xlabel('$v$')
-plt.ylabel('Velocity distribution P(v)')
-plt.title(r'Velocity histogram at $k_BT=2$')
-plt.axis([-5, 5, 0, 600])
-plt.grid(True)
-fromcollectionsimport Counter
-
-#print (Counter(VelocityValues))
-
-print (VelocityValues[:20])
-VelocityValues=list(Counter(VelocityValues).keys())
-d=list(Counter(VelocityValues).values())
-
-VelocityValues=np.asarray(VelocityValues)[:, np.newaxis]
-d=np.asarray(d)
-print (VelocityValues.shape, d.shape)
-
-plt.scatter(VelocityValues, d)
-plt.show()
-
-#2nd Degree Polynomial
-poly_feat=PolynomialFeatures(degree=20, include_bias=False)
-X_poly=poly_feat.fit_transform(VelocityValues)
-lin_reg=LinearRegression()
-poly_fit=lin_reg.fit(X_poly,d)
-
-y_plot=poly_fit.predict(X_poly)
-plt.title("Polynomial Fit")
-plt.plot(VelocityValues, y_plot, color='black', label="Fit")
-plt.show()
-
-#Decision Trees
-
-fromsklearn.treeimport DecisionTreeRegressor
-regr_1=DecisionTreeRegressor(max_depth=2)
-regr_2=DecisionTreeRegressor(max_depth=5)
-regr_3=DecisionTreeRegressor(max_depth=7)
-regr_1.fit(VelocityValues, d)
-regr_2.fit(VelocityValues, d)
-regr_3.fit(VelocityValues, d)
-
-X_test = np.arange(0.0, MCcycles, 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)
-
-plt.title("Decision Tree")
-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.show()
-
-
-
-
-
Building a tree, regression
+
Building a tree, regression
There are mainly two steps
@@ -424,7 +322,7 @@ box.
-
A top-down approach, recursive binary splitting
+
A top-down approach, recursive binary splitting
Unfortunately, it is computationally infeasible to consider every
@@ -443,7 +341,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
@@ -490,7 +388,7 @@ region contains more than five observations.
-
Pruning the tree
+
Pruning the tree
The above procedure is rather straightforward, but leads often to
@@ -509,7 +407,7 @@ parameter \( \alpha \).
-
Cost complexity pruning
+
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},
@@ -540,7 +438,7 @@ subtree corresponding to \( \alpha \).
-
A schematic procedure
+
A schematic procedure
@@ -566,7 +464,7 @@ subtree corresponding to \( \alpha \).
-
A classification tree
+
A classification tree
A classification tree is very similar to a regression tree, except
@@ -585,7 +483,7 @@ fall into that region.
-
Growing a classification tree
+
Growing a classification tree
The task of growing a
@@ -609,7 +507,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
\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
@@ -651,12 +549,15 @@ $$
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)
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees.html b/doc/pub/DecisionTrees/html/DecisionTrees.html
index e5eede0b4..024723f43 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees.html
@@ -69,39 +69,38 @@ div { text-align: justify; text-justify: inter-word; }
'sections': [('Decision trees, overarching aims', 2, None, '___sec0'),
('How do we set it up?', 2, None, '___sec1'),
('Decision trees and Regression', 2, None, '___sec2'),
- ('Maxwell-Boltzmann velocity distribution', 2, None, '___sec3'),
- ('Building a tree, regression', 2, None, '___sec4'),
+ ('Building a tree, regression', 2, None, '___sec3'),
('A top-down approach, recursive binary splitting',
2,
None,
- '___sec5'),
- ('Making a tree', 2, None, '___sec6'),
- ('Pruning the tree', 2, None, '___sec7'),
- ('Cost complexity pruning', 2, None, '___sec8'),
- ('A schematic procedure', 2, None, '___sec9'),
- ('A classification tree', 2, None, '___sec10'),
- ('Growing a classification tree', 2, None, '___sec11'),
- ('Classification tree, how to split nodes', 2, None, '___sec12'),
- ('Entropy and the ID3 algorithm', 2, None, '___sec13'),
+ '___sec4'),
+ ('Making a tree', 2, None, '___sec5'),
+ ('Pruning the tree', 2, None, '___sec6'),
+ ('Cost complexity pruning', 2, None, '___sec7'),
+ ('A schematic procedure', 2, None, '___sec8'),
+ ('A classification tree', 2, None, '___sec9'),
+ ('Growing a classification tree', 2, None, '___sec10'),
+ ('Classification tree, how to split nodes', 2, None, '___sec11'),
+ ('Entropy and the ID3 algorithm', 2, None, '___sec12'),
('Writing your own code for a classification tree',
2,
None,
- '___sec14'),
- ('Back to moons again', 2, None, '___sec15'),
- ('Playing around with regions', 2, None, '___sec16'),
- ('Regression trees', 2, None, '___sec17'),
- ('Final regressor code', 2, None, '___sec18'),
- ('Classification again: The zoo data', 2, None, '___sec19'),
- ('Pros and cons of trees, pros', 2, None, '___sec20'),
- ('Disadvantages', 2, None, '___sec21'),
- ('Bagging', 2, None, '___sec22'),
- ('Simple example, head or tail', 2, None, '___sec23'),
- ('Random forests', 2, None, '___sec24'),
- ('A simple scikit-learn example', 2, None, '___sec25'),
- ('Please, not the moons again!', 2, None, '___sec26'),
- ('Bagging examples', 2, None, '___sec27'),
- ('Then random forests', 2, None, '___sec28'),
- ('Boosting and more', 2, None, '___sec29')]}
+ '___sec13'),
+ ('Back to moons again', 2, None, '___sec14'),
+ ('Playing around with regions', 2, None, '___sec15'),
+ ('Regression trees', 2, None, '___sec16'),
+ ('Final regressor code', 2, None, '___sec17'),
+ ('Classification again: The zoo data', 2, None, '___sec18'),
+ ('Pros and cons of trees, pros', 2, None, '___sec19'),
+ ('Disadvantages', 2, None, '___sec20'),
+ ('Bagging', 2, None, '___sec21'),
+ ('Simple example, head or tail', 2, None, '___sec22'),
+ ('Random forests', 2, None, '___sec23'),
+ ('A simple scikit-learn example', 2, None, '___sec24'),
+ ('Please, not the moons again!', 2, None, '___sec25'),
+ ('Bagging examples', 2, None, '___sec26'),
+ ('Then random forests', 2, None, '___sec27'),
+ ('Boosting and more', 2, None, '___sec28')]}
end of tocinfo -->
@@ -143,7 +142,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Dec 17, 2018
+
Oct 24, 2019
@@ -296,108 +295,7 @@ plt.show()
-
Maxwell-Boltzmann velocity distribution
-
-
-
-
-
# Program to test the Metropolis algorithm with one particle at given temp in
-# one dimension
-#!/usr/bin/env python
-importnumpyasnp
-importmatplotlib.mlabasmlab
-importmatplotlib.pyplotasplt
-importrandom
-frommathimport sqrt, exp, log
-fromsklearn.preprocessingimport PolynomialFeatures
-fromsklearn.linear_modelimport LinearRegression
-# initialize the rng with a seed
-random.seed()
-# Hard coding of input parameters
-MCcycles =100000
-Temperature =2.0
-beta =1./Temperature
-InitialVelocity =-2.0
-CurrentVelocity = InitialVelocity
-Energy =0.5*InitialVelocity*InitialVelocity
-VelocityRange =10*sqrt(Temperature)
-VelocityStep =2*VelocityRange/10.
-AverageEnergy = Energy
-AverageEnergy2 = Energy*Energy
-VelocityValues = np.zeros(MCcycles)
-# The Monte Carlo sampling with Metropolis starts here
-for i inrange (1, MCcycles, 1):
- TrialVelocity = CurrentVelocity + (2.0*random.random() -1.0)*VelocityStep
- EnergyChange =0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);
- if random.random() <= exp(-beta*EnergyChange):
- CurrentVelocity = TrialVelocity
- Energy += EnergyChange
- VelocityValues[i] = CurrentVelocity
- AverageEnergy += Energy
- AverageEnergy2 += Energy*Energy
-#Final averages
-AverageEnergy = AverageEnergy/MCcycles
-AverageEnergy2 = AverageEnergy2/MCcycles
-Variance = AverageEnergy2 - AverageEnergy*AverageEnergy
-print(AverageEnergy, Variance)
-n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')
-
-plt.xlabel('$v$')
-plt.ylabel('Velocity distribution P(v)')
-plt.title(r'Velocity histogram at $k_BT=2$')
-plt.axis([-5, 5, 0, 600])
-plt.grid(True)
-fromcollectionsimport Counter
-
-#print (Counter(VelocityValues))
-
-print (VelocityValues[:20])
-VelocityValues=list(Counter(VelocityValues).keys())
-d=list(Counter(VelocityValues).values())
-
-VelocityValues=np.asarray(VelocityValues)[:, np.newaxis]
-d=np.asarray(d)
-print (VelocityValues.shape, d.shape)
-
-plt.scatter(VelocityValues, d)
-plt.show()
-
-#2nd Degree Polynomial
-poly_feat=PolynomialFeatures(degree=20, include_bias=False)
-X_poly=poly_feat.fit_transform(VelocityValues)
-lin_reg=LinearRegression()
-poly_fit=lin_reg.fit(X_poly,d)
-
-y_plot=poly_fit.predict(X_poly)
-plt.title("Polynomial Fit")
-plt.plot(VelocityValues, y_plot, color='black', label="Fit")
-plt.show()
-
-#Decision Trees
-
-fromsklearn.treeimport DecisionTreeRegressor
-regr_1=DecisionTreeRegressor(max_depth=2)
-regr_2=DecisionTreeRegressor(max_depth=5)
-regr_3=DecisionTreeRegressor(max_depth=7)
-regr_1.fit(VelocityValues, d)
-regr_2.fit(VelocityValues, d)
-regr_3.fit(VelocityValues, d)
-
-X_test = np.arange(0.0, MCcycles, 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)
-
-plt.title("Decision Tree")
-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.show()
-
-
-
-
-
Building a tree, regression
+
Building a tree, regression
There are mainly two steps
@@ -429,7 +327,7 @@ box.
-
A top-down approach, recursive binary splitting
+
A top-down approach, recursive binary splitting
Unfortunately, it is computationally infeasible to consider every
@@ -448,7 +346,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
@@ -495,7 +393,7 @@ region contains more than five observations.
-
Pruning the tree
+
Pruning the tree
The above procedure is rather straightforward, but leads often to
@@ -514,7 +412,7 @@ parameter \( \alpha \).
-
Cost complexity pruning
+
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},
@@ -545,7 +443,7 @@ subtree corresponding to \( \alpha \).
-
A schematic procedure
+
A schematic procedure
@@ -571,7 +469,7 @@ subtree corresponding to \( \alpha \).
-
A classification tree
+
A classification tree
A classification tree is very similar to a regression tree, except
@@ -590,7 +488,7 @@ fall into that region.
-
Growing a classification tree
+
Growing a classification tree
The task of growing a
@@ -614,7 +512,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
\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
@@ -656,12 +554,15 @@ $$
-
Entropy and the ID3 algorithm
+
Entropy and the ID3 algorithm
+
+
+More text to come here.
-
Writing your own code for a classification tree
+
Writing your own code for a classification tree
@@ -753,7 +654,7 @@ $$
-
Back to moons again
+
Back to moons again
@@ -825,7 +726,7 @@ plt.show()
-
Playing around with regions
+
Playing around with regions
@@ -853,7 +754,7 @@ plt.show()
-
Regression trees
+
Regression trees
@@ -875,7 +776,7 @@ tree_reg.fit(X, y)
-
Final regressor code
+
Final regressor code
@@ -953,7 +854,7 @@ plt.show()
-
Classification again: The zoo data
+
Classification again: The zoo data
@@ -981,7 +882,7 @@ prediction = treePros and cons of trees, pros
+
Pros and cons of trees, pros
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)