{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 06 - Decision Trees\n",
"\n",
"by [Alejandro Correa Bahnsen](albahnsen.com/) and [Jesus Solano](https://github.com/jesugome)\n",
"\n",
"version 1.4, January 2019\n",
"\n",
"## Part of the class [Practical Machine Learning](https://github.com/albahnsen/PracticalMachineLearningClass)\n",
"\n",
"\n",
"\n",
"This notebook is licensed under a [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/deed.en_US). Special thanks goes to [Rick Muller](http://www.cs.sandia.gov/~rmuller/), Sandia National Laboratories"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Why are we learning about decision trees?\n",
"\n",
"- Can be applied to both regression and classification problems\n",
"- Many useful properties\n",
"- Very popular\n",
"- Basis for more sophisticated models\n",
"- Have a different way of \"thinking\" than the other models we have studied"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lesson objectives\n",
"\n",
"Students will be able to:\n",
"\n",
"- Explain how a decision tree is created\n",
"- Build a decision tree model in scikit-learn\n",
"- Tune a decision tree model and explain how tuning impacts the model\n",
"- Interpret a tree diagram\n",
"- Describe the key differences between regression and classification trees\n",
"- Decide whether a decision tree is an appropriate model for a given problem"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 1: Regression trees\n",
"\n",
"Major League Baseball player data from 1986-87:\n",
"\n",
"- **Years** (x-axis): number of years playing in the major leagues\n",
"- **Hits** (y-axis): number of hits in the previous year\n",
"- **Salary** (color): low salary is blue/green, high salary is red/yellow"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Salary data](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/salary_color.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Group exercise:\n",
"\n",
"- The data above is our **training data**.\n",
"- We want to build a model that predicts the Salary of **future players** based on Years and Hits.\n",
"- 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.\n",
"- Intuitively, you want to **maximize** the similarity (or \"homogeneity\") within a given region, and **minimize** the similarity between different regions.\n",
"\n",
"Rules for segmenting:\n",
"\n",
"- You can only use **straight lines**, drawn one at a time.\n",
"- Your line must either be **vertical or horizontal**.\n",
"- Your line **stops** when it hits an existing line."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Salary regions](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/salary_regions.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Above are the regions created by a computer:\n",
"\n",
"- $R_1$: players with **less than 5 years** of experience, mean Salary of **\\$166,000 **\n",
"- $R_2$: players with **5 or more years** of experience and **less than 118 hits**, mean Salary of **\\$403,000 **\n",
"- $R_3$: players with **5 or more years** of experience and **118 hits or more**, mean Salary of **\\$846,000 **\n",
"\n",
"**Note:** Years and Hits are both integers, but the convention is to use the **midpoint** between adjacent values to label a split.\n",
"\n",
"These regions are used to make predictions on **out-of-sample data**. Thus, there are only three possible predictions! (Is this different from how **linear regression** makes predictions?)\n",
"\n",
"Below is the equivalent regression tree:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Salary tree](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/salary_tree.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"For players in the **left branch**, the mean Salary is \\$166,000, thus you label it with that value. (Salary has been divided by 1000 and log-transformed to 5.11.)\n",
"\n",
"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)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Salary tree annotated](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/salary_tree_annotated.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**What does this tree tell you about your data?**\n",
"\n",
"- Years is the most important factor determining Salary, with a lower number of Years corresponding to a lower Salary.\n",
"- For a player with a lower number of Years, Hits is not an important factor determining Salary.\n",
"- For a player with a higher number of Years, Hits is an important factor determining Salary, with a greater number of Hits corresponding to a higher Salary.\n",
"\n",
"**Question:** What do you like and dislike about decision trees so far?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Building a regression tree by hand\n",
"\n",
"Your **training data** is a tiny dataset of [used vehicle sale prices](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/vehicles_train.csv). Your goal is to **predict price** for testing data.\n",
"\n",
"1. Read the data into a Pandas DataFrame.\n",
"2. Explore the data by sorting, plotting, or split-apply-combine (aka `group_by`).\n",
"3. Decide which feature is the most important predictor, and use that to create your first splitting rule.\n",
" - Only binary splits are allowed.\n",
"4. After making your first split, split your DataFrame into two parts, and then explore each part to figure out what other splits to make.\n",
"5. Stop making splits once you are convinced that it strikes a good balance between underfitting and overfitting.\n",
" - Your goal is to build a model that generalizes well.\n",
" - You are allowed to split on the same variable multiple times!\n",
"6. Draw your tree, labeling the leaves with the mean price for the observations in that region.\n",
" - Make sure nothing is backwards: You follow the **left branch** if the rule is true, and the **right branch** if the rule is false."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How does a computer build a regression tree?\n",
"\n",
"**Ideal approach:** Consider every possible partition of the feature space (computationally infeasible)\n",
"\n",
"**\"Good enough\" approach:** recursive binary splitting\n",
"\n",
"1. Begin at the top of the tree.\n",
"2. For **every feature**, examine **every possible cutpoint**, and choose the feature and cutpoint such that the resulting tree has the lowest possible mean squared error (MSE). Make that split.\n",
"3. Examine the two resulting regions, and again make a **single split** (in one of the regions) to minimize the MSE.\n",
"4. Keep repeating step 3 until a **stopping criterion** is met:\n",
" - maximum tree depth (maximum number of splits required to arrive at a leaf)\n",
" - minimum number of observations in a leaf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Demo: Choosing the ideal cutpoint for a given feature"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# vehicle data\n",
"import pandas as pd\n",
"url = 'https://github.com/albahnsen/PracticalMachineLearningClass/raw/master/datasets/vehicles_train.csv'\n",
"train = pd.read_csv(url)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
"
],
"text/plain": [
" feature importance\n",
"0 year 0.798744\n",
"1 miles 0.201256\n",
"2 doors 0.000000\n",
"3 vtype 0.000000"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# \"Gini importance\" of each feature: the (normalized) total reduction of error brought by that feature\n",
"pd.DataFrame({'feature':feature_cols, 'importance':treereg.feature_importances_})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating a tree diagram"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"# create a Graphviz file\n",
"from sklearn.tree import export_graphviz\n",
"export_graphviz(treereg, out_file='tree_vehicles.dot', feature_names=feature_cols)\n",
"\n",
"# At the command line, run this to convert to PNG:\n",
"# dot -Tpng tree_vehicles.dot -o tree_vehicles.png"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Tree for vehicle data](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/tree_vehicles.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Reading the internal nodes:\n",
"\n",
"- **samples:** number of observations in that node before splitting\n",
"- **mse:** MSE calculated by comparing the actual response values in that node against the mean response value in that node\n",
"- **rule:** rule used to split that node (go left if true, go right if false)\n",
"\n",
"Reading the leaves:\n",
"\n",
"- **samples:** number of observations in that node\n",
"- **value:** mean response value in that node\n",
"- **mse:** MSE calculated by comparing the actual response values in that node against \"value\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Making predictions for the testing data"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
price
\n",
"
year
\n",
"
miles
\n",
"
doors
\n",
"
vtype
\n",
"
\n",
" \n",
" \n",
"
\n",
"
0
\n",
"
3000
\n",
"
2003
\n",
"
130000
\n",
"
4
\n",
"
1
\n",
"
\n",
"
\n",
"
1
\n",
"
6000
\n",
"
2005
\n",
"
82500
\n",
"
4
\n",
"
0
\n",
"
\n",
"
\n",
"
2
\n",
"
12000
\n",
"
2010
\n",
"
60000
\n",
"
2
\n",
"
0
\n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" price year miles doors vtype\n",
"0 3000 2003 130000 4 1\n",
"1 6000 2005 82500 4 0\n",
"2 12000 2010 60000 2 0"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# read the testing data\n",
"url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/vehicles_test.csv'\n",
"test = pd.read_csv(url)\n",
"test['vtype'] = test.vtype.map({'car':0, 'truck':1})\n",
"test"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Question:** Using the tree diagram above, what predictions will the model make for each observation?"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 4000., 5000., 13500.])"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# use fitted model to make predictions on testing data\n",
"X_test = test[feature_cols]\n",
"y_test = test.price\n",
"y_pred = treereg.predict(X_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1190.2380714238084"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# calculate RMSE\n",
"from sklearn.metrics import mean_squared_error\n",
"np.sqrt(mean_squared_error(y_test, y_pred))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 2: Classification trees\n",
"\n",
"**Example:** Predict whether Barack Obama or Hillary Clinton will win the Democratic primary in a particular county in 2008:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Obama-Clinton decision tree](https://github.com/justmarkham/DAT8/raw/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/obama_clinton_tree.jpg)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Questions:**\n",
"\n",
"- What are the observations? How many observations are there?\n",
"- What is the response variable?\n",
"- What are the features?\n",
"- What is the most predictive feature?\n",
"- Why does the tree split on high school graduation rate twice in a row?\n",
"- What is the class prediction for the following county: 15% African-American, 90% high school graduation rate, located in the South, high poverty, high population density?\n",
"- What is the predicted probability for that same county?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing regression trees and classification trees\n",
"\n",
"|regression trees|classification trees|\n",
"|---|---|\n",
"|predict a continuous response|predict a categorical response|\n",
"|predict using mean response of each leaf|predict using most commonly occuring class of each leaf|\n",
"|splits are chosen to minimize MSE|splits are chosen to minimize Gini index (discussed below)|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Splitting criteria for classification trees\n",
"\n",
"Common options for the splitting criteria:\n",
"\n",
"- **classification error rate:** fraction of training observations in a region that don't belong to the most common class\n",
"- **Gini index:** measure of total variance across classes in a region"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example of classification error rate\n",
"\n",
"Pretend we are predicting whether someone buys an iPhone or an Android:\n",
"\n",
"- At a particular node, there are **25 observations** (phone buyers), of whom **10 bought iPhones and 15 bought Androids**.\n",
"- Since the majority class is **Android**, that's our prediction for all 25 observations, and thus the classification error rate is **10/25 = 40%**.\n",
"\n",
"Our goal in making splits is to **reduce the classification error rate**. Let's try splitting on gender:\n",
"\n",
"- **Males:** 2 iPhones and 12 Androids, thus the predicted class is Android\n",
"- **Females:** 8 iPhones and 3 Androids, thus the predicted class is iPhone\n",
"- Classification error rate after this split would be **5/25 = 20%**\n",
"\n",
"Compare that with a split on age:\n",
"\n",
"- **30 or younger:** 4 iPhones and 8 Androids, thus the predicted class is Android\n",
"- **31 or older:** 6 iPhones and 7 Androids, thus the predicted class is Android\n",
"- Classification error rate after this split would be **10/25 = 40%**\n",
"\n",
"The decision tree algorithm will try **every possible split across all features**, and choose the split that **reduces the error rate the most.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example of Gini index\n",
"\n",
"Calculate the Gini index before making a split:\n",
"\n",
"$$1 - \\left(\\frac {iPhone} {Total}\\right)^2 - \\left(\\frac {Android} {Total}\\right)^2 = 1 - \\left(\\frac {10} {25}\\right)^2 - \\left(\\frac {15} {25}\\right)^2 = 0.48$$\n",
"\n",
"- The **maximum value** of the Gini index is 0.5, and occurs when the classes are perfectly balanced in a node.\n",
"- The **minimum value** of the Gini index is 0, and occurs when there is only one class represented in a node.\n",
"- A node with a lower Gini index is said to be more \"pure\".\n",
"\n",
"Evaluating the split on **gender** using Gini index:\n",
"\n",
"$$\\text{Males: } 1 - \\left(\\frac {2} {14}\\right)^2 - \\left(\\frac {12} {14}\\right)^2 = 0.24$$\n",
"$$\\text{Females: } 1 - \\left(\\frac {8} {11}\\right)^2 - \\left(\\frac {3} {11}\\right)^2 = 0.40$$\n",
"$$\\text{Weighted Average: } 0.24 \\left(\\frac {14} {25}\\right) + 0.40 \\left(\\frac {11} {25}\\right) = 0.31$$\n",
"\n",
"Evaluating the split on **age** using Gini index:\n",
"\n",
"$$\\text{30 or younger: } 1 - \\left(\\frac {4} {12}\\right)^2 - \\left(\\frac {8} {12}\\right)^2 = 0.44$$\n",
"$$\\text{31 or older: } 1 - \\left(\\frac {6} {13}\\right)^2 - \\left(\\frac {7} {13}\\right)^2 = 0.50$$\n",
"$$\\text{Weighted Average: } 0.44 \\left(\\frac {12} {25}\\right) + 0.50 \\left(\\frac {13} {25}\\right) = 0.47$$\n",
"\n",
"Again, the decision tree algorithm will try **every possible split**, and will choose the split that **reduces the Gini index (and thus increases the \"node purity\") the most.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Comparing classification error rate and Gini index\n",
"\n",
"- 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.\n",
"- Node purity is important because we're interested in the **class proportions** in each region, since that's how we calculate the **predicted probability** of each class.\n",
"- scikit-learn's default splitting criteria for classification trees is Gini index.\n",
"\n",
"Note: There is another common splitting criteria called **cross-entropy**. It's numerically similar to Gini index, but slower to compute, thus it's not as popular as Gini index."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Building a classification tree in scikit-learn"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll build a classification tree using the Titanic data:"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
PassengerId
\n",
"
Survived
\n",
"
Pclass
\n",
"
Name
\n",
"
Sex
\n",
"
Age
\n",
"
SibSp
\n",
"
Parch
\n",
"
Ticket
\n",
"
Fare
\n",
"
Cabin
\n",
"
Embarked
\n",
"
Embarked_Q
\n",
"
Embarked_S
\n",
"
\n",
" \n",
" \n",
"
\n",
"
0
\n",
"
1
\n",
"
0
\n",
"
3
\n",
"
Braund, Mr. Owen Harris
\n",
"
1
\n",
"
22.0
\n",
"
1
\n",
"
0
\n",
"
A/5 21171
\n",
"
7.2500
\n",
"
NaN
\n",
"
S
\n",
"
0
\n",
"
1
\n",
"
\n",
"
\n",
"
1
\n",
"
2
\n",
"
1
\n",
"
1
\n",
"
Cumings, Mrs. John Bradley (Florence Briggs Th...
\n",
"
0
\n",
"
38.0
\n",
"
1
\n",
"
0
\n",
"
PC 17599
\n",
"
71.2833
\n",
"
C85
\n",
"
C
\n",
"
0
\n",
"
0
\n",
"
\n",
"
\n",
"
2
\n",
"
3
\n",
"
1
\n",
"
3
\n",
"
Heikkinen, Miss. Laina
\n",
"
0
\n",
"
26.0
\n",
"
0
\n",
"
0
\n",
"
STON/O2. 3101282
\n",
"
7.9250
\n",
"
NaN
\n",
"
S
\n",
"
0
\n",
"
1
\n",
"
\n",
"
\n",
"
3
\n",
"
4
\n",
"
1
\n",
"
1
\n",
"
Futrelle, Mrs. Jacques Heath (Lily May Peel)
\n",
"
0
\n",
"
35.0
\n",
"
1
\n",
"
0
\n",
"
113803
\n",
"
53.1000
\n",
"
C123
\n",
"
S
\n",
"
0
\n",
"
1
\n",
"
\n",
"
\n",
"
4
\n",
"
5
\n",
"
0
\n",
"
3
\n",
"
Allen, Mr. William Henry
\n",
"
1
\n",
"
35.0
\n",
"
0
\n",
"
0
\n",
"
373450
\n",
"
8.0500
\n",
"
NaN
\n",
"
S
\n",
"
0
\n",
"
1
\n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" PassengerId Survived Pclass \\\n",
"0 1 0 3 \n",
"1 2 1 1 \n",
"2 3 1 3 \n",
"3 4 1 1 \n",
"4 5 0 3 \n",
"\n",
" Name Sex Age SibSp Parch \\\n",
"0 Braund, Mr. Owen Harris 1 22.0 1 0 \n",
"1 Cumings, Mrs. John Bradley (Florence Briggs Th... 0 38.0 1 0 \n",
"2 Heikkinen, Miss. Laina 0 26.0 0 0 \n",
"3 Futrelle, Mrs. Jacques Heath (Lily May Peel) 0 35.0 1 0 \n",
"4 Allen, Mr. William Henry 1 35.0 0 0 \n",
"\n",
" Ticket Fare Cabin Embarked Embarked_Q Embarked_S \n",
"0 A/5 21171 7.2500 NaN S 0 1 \n",
"1 PC 17599 71.2833 C85 C 0 0 \n",
"2 STON/O2. 3101282 7.9250 NaN S 0 1 \n",
"3 113803 53.1000 C123 S 0 1 \n",
"4 373450 8.0500 NaN S 0 1 "
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# read in the data\n",
"url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/titanic.csv'\n",
"titanic = pd.read_csv(url)\n",
"\n",
"# encode female as 0 and male as 1\n",
"titanic['Sex'] = titanic.Sex.map({'female':0, 'male':1})\n",
"\n",
"# fill in the missing values for age with the median age\n",
"titanic.Age.fillna(titanic.Age.median(), inplace=True)\n",
"\n",
"# create a DataFrame of dummy variables for Embarked\n",
"embarked_dummies = pd.get_dummies(titanic.Embarked, prefix='Embarked')\n",
"embarked_dummies.drop(embarked_dummies.columns[0], axis=1, inplace=True)\n",
"\n",
"# concatenate the original DataFrame and the dummy DataFrame\n",
"titanic = pd.concat([titanic, embarked_dummies], axis=1)\n",
"\n",
"# print the updated DataFrame\n",
"titanic.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- **Survived:** 0=died, 1=survived (response variable)\n",
"- **Pclass:** 1=first class, 2=second class, 3=third class\n",
" - What will happen if the tree splits on this feature?\n",
"- **Sex:** 0=female, 1=male\n",
"- **Age:** numeric value\n",
"- **Embarked:** C or Q or S"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"# define X and y\n",
"feature_cols = ['Pclass', 'Sex', 'Age', 'Embarked_Q', 'Embarked_S']\n",
"X = titanic[feature_cols]\n",
"y = titanic.Survived"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,\n",
" max_features=None, max_leaf_nodes=None,\n",
" min_impurity_decrease=0.0, min_impurity_split=None,\n",
" min_samples_leaf=1, min_samples_split=2,\n",
" min_weight_fraction_leaf=0.0, presort=False, random_state=1,\n",
" splitter='best')"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# fit a classification tree with max_depth=3 on all data\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"treeclf = DecisionTreeClassifier(max_depth=3, random_state=1)\n",
"treeclf.fit(X, y)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"# create a Graphviz file\n",
"export_graphviz(treeclf, out_file='tree_titanic.dot', feature_names=feature_cols)\n",
"\n",
"# At the command line, run this to convert to PNG:\n",
"# dot -Tpng tree_titanic.dot -o tree_titanic.png"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Tree for Titanic data](https://raw.githubusercontent.com/justmarkham/DAT8/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/tree_titanic.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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**, though it did increase the **node purity**, which is important because it increases the accuracy of our predicted probabilities."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
feature
\n",
"
importance
\n",
"
\n",
" \n",
" \n",
"
\n",
"
0
\n",
"
Pclass
\n",
"
0.242664
\n",
"
\n",
"
\n",
"
1
\n",
"
Sex
\n",
"
0.655584
\n",
"
\n",
"
\n",
"
2
\n",
"
Age
\n",
"
0.064494
\n",
"
\n",
"
\n",
"
3
\n",
"
Embarked_Q
\n",
"
0.000000
\n",
"
\n",
"
\n",
"
4
\n",
"
Embarked_S
\n",
"
0.037258
\n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" feature importance\n",
"0 Pclass 0.242664\n",
"1 Sex 0.655584\n",
"2 Age 0.064494\n",
"3 Embarked_Q 0.000000\n",
"4 Embarked_S 0.037258"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# compute the feature importances\n",
"pd.DataFrame({'feature':feature_cols, 'importance':treeclf.feature_importances_})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 3: Comparing decision trees with other models\n",
"\n",
"**Advantages of decision trees:**\n",
"\n",
"- Can be used for regression or classification\n",
"- Can be displayed graphically\n",
"- Highly interpretable\n",
"- Can be specified as a series of rules, and more closely approximate human decision-making than other models\n",
"- Prediction is fast\n",
"- Features don't need scaling\n",
"- Automatically learns feature interactions\n",
"- Tends to ignore irrelevant features\n",
"- Non-parametric (will outperform linear models if relationship between features and response is highly non-linear)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Trees versus linear models](https://raw.githubusercontent.com/justmarkham/DAT8/226791169b1cc6df8e8845c12e34e748d5ffaa85/notebooks/images/tree_vs_linear.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Disadvantages of decision trees:**\n",
"\n",
"- Performance is (generally) not competitive with the best supervised learning methods\n",
"- Can easily overfit the training data (tuning is required)\n",
"- Small variations in the data can result in a completely different tree (high variance)\n",
"- Recursive binary splitting makes \"locally optimal\" decisions that may not result in a globally optimal tree\n",
"- Doesn't tend to work well if the classes are highly unbalanced\n",
"- Doesn't tend to work well with very small datasets"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
}
},
"nbformat": 4,
"nbformat_minor": 1
}