Path: blob/master/lessons/lesson_11/decision_trees (done).ipynb
1904 views
Decision Trees
Author: Joseph Nelson (DC)
Adapted from Chapter 8 of An Introduction to Statistical Learning
Learning Objectives
Students will be able to:
Explain how a decision tree is created.
Build a decision tree model in scikit-learn.
Tune a decision tree model and explain how tuning impacts the model.
Interpret a tree diagram.
Describe the key differences between regression and classification trees.
Decide whether or not a decision tree is an appropriate model for a given problem.
Lesson Guide
Introduction
In this lesson, we will be exploring decision trees and random forests. These are non-parametric models that can either be used for regression or classification.
You are likely very familiar with decision trees already! For example, take this graphic from the New York Times. It explains how to predict whether Barack Obama or Hillary Clinton will win the Democratic primary in a particular county in 2008. At the same time, it informs which features might be most important to predict an Obama or Clinton win:
Random forests are groups of decision trees created using different subsets and feature sets of the training data. Each tree "votes" on a classification.
Why are we learning about decision trees?
They can be applied to both regression and classification problems.
They are easy to explain to others (interpretable).
They are very popular among data scientists.
They are the basis for more sophisticated models.
They have a different way of "thinking" than the other models we have studied.
Part 1: Regression Trees
In this section, we will make decision trees that predict numeric data. Instead of returning a class, we will return a single numeric value for each set of conditions.
For example, the following tree predicts Major League Baseball salaries based on Years playing in the major leagues and Hits the previous year. Only three different salaries are ever predicted (the average salaries of players that meet each set of conditions):
The salary has been divided by 1,000 and log-normalized, for example a salary of $166,000 refers to the number:
$$5.11 = \ln(\$166000/1000)$$
Similarly, 6.00 is $403,000, and 6.74 is $846,000. A natural log transform was made because some salaries are much higher than others, leading to a non-ideal long-tail distribution.
Our dataset will be Major League Baseball player data from 1986–87:
Years (x-axis): Number of years playing in the major leagues.
Hits (y-axis): Number of hits in the previous year.
Salary (color): Low salary is blue/green, high salary is red/yellow.
Group Exercise
The data set above is our training data.
We want to build a model that predicts the salary of future players based on years and hits.
We are going to "segment" the feature space into regions, and then use the mean salary in each region as the predicted Salary for future players.
Intuitively, you want to maximize the similarity (or "homogeneity") within a given region, and minimize the similarity between different regions.
Rules for Segmenting
You can only use straight lines that are drawn one at a time.
Your line must either be vertical or horizontal.
Your line stops when it hits an existing line.
Solution (only look AFTER the group exercise!):
As shown in the solution above, the regions created by a computer are:
: Players with less than 5 years of experience and a mean salary of $166,000.
: Players with 5 or more years of experience and less than 118 hits and mean salary of $403,000.
: Players with 5 or more years of experience and 118 hits or more and mean Salary of $846,000.
Note: Years and hits are both integers, but the convention is to use the midpoint between adjacent values to label a split.
These regions are used to make predictions for out-of-sample data. Thus, there are only three possible predictions! (Is this different from how linear regression makes predictions?)
Below is the equivalent regression tree:
The first split is years < 4.5, thus that split goes at the top of the tree. When a splitting rule is true, you follow the left branch. When a splitting rule is false, you follow the right branch.
For players in the left branch, the mean salary is $166,000, thus you label it with that value. (Salary has been divided by 1,000 and log-transformed to 5.11.)
For players in the right branch, there is a further split on hits < 117.5, dividing players into two more salary regions: $403,000 (transformed to 6.00), and $846,000 (transformed to 6.74).
What does this tree tell you about your data?
Years is the most important factor determining salary, with a lower number of years corresponding to a lower salary.
For a player with a lower number of years, hits is not an important factor in determining salary.
For a player with a higher number of years, hits is an important factor in determining salary, with a greater number of hits corresponding to a higher salary.
Question: What do you like and dislike about decision trees so far?
Building a Regression Tree by Hand
Your training data is a tiny data set of used vehicle sale prices. Your goal is to predict price for testing data.
Read the data into a Pandas DataFrame.
Explore the data by sorting, plotting, or performing split-apply-combine (a.k.a.
group_by
).Decide which feature is the most important predictor, and use that to create your first splitting rule.
Only binary splits are allowed.
After making your first split, split your DataFrame into two parts and then explore each part to figure out what other splits to make.
Stop making splits once you are convinced that it strikes a good balance between underfitting and overfitting.
Your goal is to build a model that generalizes well.
You are allowed to split on the same variable multiple times.
Draw your tree, labeling the leaves with the mean price for the observations in that region.
Make sure nothing is backwards: You follow the left branch if the rule is true and the right branch if the rule is false.
How Does a Computer Build a Regression Tree?
Ideal approach: Considering every possible partition of the feature space (computationally infeasible).
"Good enough" approach: Recursive binary splitting.
Begin at the top of the tree.
For every feature, examine every possible cutpoint, and choose the feature and cutpoint so that the resulting tree has the lowest possible mean squared error (MSE). Make that split.
Examine the two resulting regions. Once again, make a single split (in one of the regions) to minimize the MSE.
Keep repeating Step 3 until a stopping criterion is met:
Maximum tree depth (maximum number of splits required to arrive at a leaf).
Minimum number of observations in a leaf.
This is a greedy algorithm because it makes locally optimal decisions -- it takes the best split at each step. A greedy algorithm hopes that a series of locally optimal decisions might be optimal overall; however, this is not always the case. For example:
Always eating cookies to maximize your immediate happiness (greedy) might not lead to optimal overall happiness.
In our case, reorganizing parts of the tree already constructed based on future splits might result in a better model overall.
Recap: Before every split, we repeat this process for every feature and choose the feature and cutpoint that produce the lowest MSE.
The training error continues to go down as the tree size increases (due to overfitting), but the lowest cross-validation error occurs for a tree with three leaves.
Note that if we make a complete tree (where every data point is boxed into its own region), then we will achieve perfect training accuracy. However, then outliers in the training data will greatly affect the model.
Or, we could write a loop to try a range of values:
Creating a Tree Diagram
To create a tree diagram, we will use the Graphviz library for displaying graph data structures.
Surprisingly, every tree is just a graph in disguise! A graph is a tree only if there is exactly one vertex with no incoming edge (the root), while all other vertices have exactly one incoming edge (representing its parent).
Reading the internal nodes:
samples: Number of observations in that node before splitting.
mse: MSE calculated by comparing the actual response values in that node against the mean response value in that node.
rule: Rule used to split that node (go left if true, go right if false).
Reading the leaves:
samples: Number of observations in that node.
value: Mean response value in that node.
mse: MSE calculated by comparing the actual response values in that node against "value."
Question: Using the tree diagram above, what predictions will the model make for each observation?
Questions:
What are the observations? How many observations are there?
What is the response variable?
What are the features?
What is the most predictive feature?
Why does the tree split on high school graduation rate twice in a row?
What is the class prediction for the following county: 15 percent African American, 90 percent high school graduation rate, located in the South, high poverty, high population density?
What is the predicted probability for that same county?
Comparing Regression Trees and Classification Trees
Regression Trees | Classification Trees |
---|---|
Predict a continuous response. | Predict a categorical response. |
Predict using mean response of each leaf. | Predict using most commonly occurring class of each leaf. |
Splits are chosen to minimize MSE. | Splits are chosen to minimize Gini index (discussed below). |
Example: Classification Error Rate
Pretend we are predicting whether or not someone will buy an iPhone or an Android:
At a particular node, there are 25 observations (phone buyers) of whom 10 bought iPhones and 15 bought Androids.
As the majority class is Android, that's our prediction for all 25 observations, and thus the classification error rate is 10/25 = 40%.
Our goal in making splits is to reduce the classification error rate. Let's try splitting on gender:
Males: Two iPhones and 12 Androids, thus the predicted class is Android.
Females: Eight iPhones and three Androids, thus the predicted class is iPhone.
Classification error rate after this split would be 5/25 = 20%.
Compare that with a split on age:
30 or younger: Four iPhones and eight Androids, thus the predicted class is Android.
31 or older: Six iPhones and seven Androids, thus the predicted class is Android.
Classification error rate after this split would be 10/25 = 40%.
The decision tree algorithm will try every possible split across all features and choose the one that reduces the error rate the most.
Example: Gini Index
Calculate the Gini index before making a split:
The maximum value of the Gini index is 0.5 and occurs when the classes are perfectly balanced in a node.
The minimum value of the Gini index is 0 and occurs when there is only one class represented in a node.
A node with a lower Gini index is said to be more "pure."
Evaluating the split on gender using the Gini index:
Evaluating the split on age using the Gini index:
Again, the decision tree algorithm will try every possible split and will choose the one that reduces the Gini index (and thus increases the "node purity") the most.
You can think of this as each split increasing the accuracy of predictions. If there is some error at a node, then splitting at that node will result in two nodes with a higher average "node purity" than the original. So, we ensure continually better fits to the training data by continually splitting nodes.
Comparing Classification Error Rate and Gini Index
Gini index is generally preferred because it will make splits that increase node purity, even if that split does not change the classification error rate.
Node purity is important because we're interested in the class proportions in each region, as that's how we calculate the predicted probability of each class.
scikit-learn's default splitting criteria for classification trees is Gini index.
Note: There is another common splitting criteria called cross-entropy. It's numerically similar to Gini index but slower to compute. So, it's not as popular as Gini index.
We'll build a classification tree using the Titanic survival data set:
Survived: 0=died, 1=survived (response variable)
Pclass: 1=first class, 2=second class, 3=third class
What will happen if the tree splits on this feature?
Sex: 0=female, 1=male
Age: Numeric value
Embarked: C or Q or S
Notice the split in the bottom right; the same class is predicted in both of its leaves. That split didn't affect the classification error rate, although it did increase the node purity. This is important because it increases the accuracy of our predicted probabilities.
A useful side effect of measures such as the Gini index is that they can be used give some indication of feature importance:
Summary: Comparing Decision Trees With Other Models
Advantages of decision trees:
They can be used for regression or classification.
They can be displayed graphically.
They are highly interpretable.
They can be specified as a series of rules, and more closely approximate human decision-making than other models.
Prediction is fast.
Their features don't need scaling.
They authomatically learn feature interactions.
Tends to ignore irrelevant features.
They are non-parametric (i.e. will outperform linear models if the relationship between features and response is highly non-linear).
Disadvantages of decision trees:
Their performance is (generally) not competitive with the best supervised learning methods.
They can easily overfit the training data (tuning is required).
Small variations in the data can result in a completely different tree (high variance).
Recursive binary splitting makes "locally optimal" decisions that may not result in a globally optimal tree.
They don't tend to work well if the classes are highly unbalanced.
They don't tend to work well with very small data sets.