{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Decision Trees\n", "\n", "*Adapted from Chapter 8 of [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/)*" ] }, { "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](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](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](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](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": { "collapsed": false }, "outputs": [], "source": [ "# vehicle data\n", "import pandas as pd\n", "url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/vehicles_train.csv'\n", "train = pd.read_csv(url)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
priceyearmilesdoorsvtypeprediction
0220002012130002car6571.428571
1140002010300002car6571.428571
2130002010735004car6571.428571
395002009780004car6571.428571
490002007470004car6571.428571
5400020061240002car6571.428571
6300020041770004car6571.428571
7200020042090004truck6571.428571
8300020031380002car6571.428571
9190020031600004car6571.428571
10250020031900002truck6571.428571
1150002001620004car6571.428571
12180019991630002truck6571.428571
13130019971380004car6571.428571
\n", "
" ], "text/plain": [ " price year miles doors vtype prediction\n", "0 22000 2012 13000 2 car 6571.428571\n", "1 14000 2010 30000 2 car 6571.428571\n", "2 13000 2010 73500 4 car 6571.428571\n", "3 9500 2009 78000 4 car 6571.428571\n", "4 9000 2007 47000 4 car 6571.428571\n", "5 4000 2006 124000 2 car 6571.428571\n", "6 3000 2004 177000 4 car 6571.428571\n", "7 2000 2004 209000 4 truck 6571.428571\n", "8 3000 2003 138000 2 car 6571.428571\n", "9 1900 2003 160000 4 car 6571.428571\n", "10 2500 2003 190000 2 truck 6571.428571\n", "11 5000 2001 62000 4 car 6571.428571\n", "12 1800 1999 163000 2 truck 6571.428571\n", "13 1300 1997 138000 4 car 6571.428571" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# before splitting anything, just predict the mean of the entire dataset\n", "train['prediction'] = train.price.mean()\n", "train" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5936.9819859959835" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calculate RMSE for those predictions\n", "from sklearn import metrics\n", "import numpy as np\n", "np.sqrt(metrics.mean_squared_error(train.price, train.prediction))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# define a function that calculates the RMSE for a given split of miles\n", "def mileage_split(miles):\n", " lower_mileage_price = train[train.miles < miles].price.mean()\n", " higher_mileage_price = train[train.miles >= miles].price.mean()\n", " train['prediction'] = np.where(train.miles < miles, lower_mileage_price, higher_mileage_price)\n", " return np.sqrt(metrics.mean_squared_error(train.price, train.prediction))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "RMSE: 3984.09174254\n" ] }, { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
priceyearmilesdoorsvtypeprediction
0220002012130002car15000.000000
1140002010300002car15000.000000
2130002010735004car4272.727273
395002009780004car4272.727273
490002007470004car15000.000000
5400020061240002car4272.727273
6300020041770004car4272.727273
7200020042090004truck4272.727273
8300020031380002car4272.727273
9190020031600004car4272.727273
10250020031900002truck4272.727273
1150002001620004car4272.727273
12180019991630002truck4272.727273
13130019971380004car4272.727273
\n", "
" ], "text/plain": [ " price year miles doors vtype prediction\n", "0 22000 2012 13000 2 car 15000.000000\n", "1 14000 2010 30000 2 car 15000.000000\n", "2 13000 2010 73500 4 car 4272.727273\n", "3 9500 2009 78000 4 car 4272.727273\n", "4 9000 2007 47000 4 car 15000.000000\n", "5 4000 2006 124000 2 car 4272.727273\n", "6 3000 2004 177000 4 car 4272.727273\n", "7 2000 2004 209000 4 truck 4272.727273\n", "8 3000 2003 138000 2 car 4272.727273\n", "9 1900 2003 160000 4 car 4272.727273\n", "10 2500 2003 190000 2 truck 4272.727273\n", "11 5000 2001 62000 4 car 4272.727273\n", "12 1800 1999 163000 2 truck 4272.727273\n", "13 1300 1997 138000 4 car 4272.727273" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calculate RMSE for tree which splits on miles < 50000\n", "print 'RMSE:', mileage_split(50000)\n", "train" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "RMSE: 3530.14653008\n" ] }, { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
priceyearmilesdoorsvtypeprediction
0220002012130002car12083.333333
1140002010300002car12083.333333
2130002010735004car12083.333333
395002009780004car12083.333333
490002007470004car12083.333333
5400020061240002car2437.500000
6300020041770004car2437.500000
7200020042090004truck2437.500000
8300020031380002car2437.500000
9190020031600004car2437.500000
10250020031900002truck2437.500000
1150002001620004car12083.333333
12180019991630002truck2437.500000
13130019971380004car2437.500000
\n", "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
featureimportance
0year0.798744
1miles0.201256
2doors0.000000
3vtype0.000000
\n", "
" ], "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": 18, "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": 19, "metadata": { "collapsed": false }, "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](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": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
priceyearmilesdoorsvtype
03000200313000041
1600020058250040
21200020106000020
\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": 20, "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": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 4000., 5000., 13500.])" ] }, "execution_count": 21, "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": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1190.2380714238084" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calculate RMSE\n", "np.sqrt(metrics.mean_squared_error(y_test, y_pred))" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "7937.2539331937714" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calculate RMSE for your own tree!\n", "y_test = [3000, 6000, 12000]\n", "y_pred = [0, 0, 0]\n", "from sklearn import metrics\n", "np.sqrt(metrics.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](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": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedEmbarked_QEmbarked_S
0103Braund, Mr. Owen Harris12210A/5 211717.2500NaNS01
1211Cumings, Mrs. John Bradley (Florence Briggs Th...03810PC 1759971.2833C85C00
2313Heikkinen, Miss. Laina02600STON/O2. 31012827.9250NaNS01
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)0351011380353.1000C123S01
4503Allen, Mr. William Henry135003734508.0500NaNS01
\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 1 0 \n", "1 Cumings, Mrs. John Bradley (Florence Briggs Th... 0 38 1 0 \n", "2 Heikkinen, Miss. Laina 0 26 0 0 \n", "3 Futrelle, Mrs. Jacques Heath (Lily May Peel) 0 35 1 0 \n", "4 Allen, Mr. William Henry 1 35 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": 24, "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": 25, "metadata": { "collapsed": false }, "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": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,\n", " max_features=None, max_leaf_nodes=None, min_samples_leaf=1,\n", " min_samples_split=2, min_weight_fraction_leaf=0.0,\n", " random_state=1, splitter='best')" ] }, "execution_count": 26, "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": 27, "metadata": { "collapsed": false }, "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](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": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
featureimportance
0Pclass0.242664
1Sex0.655584
2Age0.064494
3Embarked_Q0.000000
4Embarked_S0.037258
\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": 28, "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](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 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 }