Files
Morten Hjorth-Jensen a44ee6723f updated ml book
2021-04-25 15:29:13 -04:00

1302 lines
51 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Decision trees, overarching aims\n",
"\n",
"\n",
"We start here with the most basic algorithm, the so-called decision\n",
"tree. With this basic algorithm we can in turn build more complex\n",
"networks, spanning from homogeneous and heterogenous forests (bagging,\n",
"random forests and more) to one of the most popular supervised\n",
"algorithms nowadays, the extreme gradient boosting, or just\n",
"XGBoost. But let us start with the simplest possible ingredient.\n",
"\n",
"Decision trees are supervised learning algorithms used for both,\n",
"classification and regression tasks.\n",
"\n",
"\n",
"The main idea of decision trees\n",
"is to find those descriptive features which contain the most\n",
"**information** regarding the target feature and then split the dataset\n",
"along the values of these features such that the target feature values\n",
"for the resulting underlying datasets are as pure as possible.\n",
"\n",
"The descriptive features which reproduce best the target/output features are normally said\n",
"to be the most informative ones. The process of finding the **most\n",
"informative** feature is done until we accomplish a stopping criteria\n",
"where we then finally end up in so called **leaf nodes**. \n",
"\n",
"## Basics of a tree\n",
"\n",
"A decision tree is typically divided into a **root node**, the **interior nodes**,\n",
"and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n",
"\n",
"The leaf nodes\n",
"contain the predictions we will make for new query instances presented\n",
"to our trained model. This is possible since the model has \n",
"learned the underlying structure of the training data and hence can,\n",
"given some assumptions, make predictions about the target feature value\n",
"(class) of unseen query instances.\n",
"\n",
"\n",
"## General Features\n",
"\n",
"The overarching approach to decision trees is a top-down approach.\n",
"\n",
"* A leaf provides the classification of a given instance.\n",
"\n",
"* A node specifies a test of some attribute of the instance.\n",
"\n",
"* A branch corresponds to a possible values of an attribute.\n",
"\n",
"* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n",
"\n",
"This process is then repeated for the subtree rooted at the new\n",
"node.\n",
"\n",
"\n",
"\n",
"In simplified terms, the process of training a decision tree and\n",
"predicting the target features of query instances is as follows:\n",
"\n",
"1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n",
"\n",
"2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n",
"\n",
"3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n",
"\n",
"4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n",
"\n",
"Then we are essentially done!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"steps=250\n",
"\n",
"distance=0\n",
"x=0\n",
"distance_list=[]\n",
"steps_list=[]\n",
"while x<steps:\n",
" distance+=np.random.randint(-1,2)\n",
" distance_list.append(distance)\n",
" x+=1\n",
" steps_list.append(x)\n",
"plt.plot(steps_list,distance_list, color='green', label=\"Random Walk Data\")\n",
"\n",
"steps_list=np.asarray(steps_list)\n",
"distance_list=np.asarray(distance_list)\n",
"\n",
"X=steps_list[:,np.newaxis]\n",
"\n",
"#Polynomial fits\n",
"\n",
"#Degree 2\n",
"poly_features=PolynomialFeatures(degree=2, include_bias=False)\n",
"X_poly=poly_features.fit_transform(X)\n",
"\n",
"lin_reg=LinearRegression()\n",
"poly_fit=lin_reg.fit(X_poly,distance_list)\n",
"b=lin_reg.coef_\n",
"c=lin_reg.intercept_\n",
"print (\"2nd degree coefficients:\")\n",
"print (\"zero power: \",c)\n",
"print (\"first power: \", b[0])\n",
"print (\"second power: \",b[1])\n",
"\n",
"z = np.arange(0, steps, .01)\n",
"z_mod=b[1]*z**2+b[0]*z+c\n",
"\n",
"fit_mod=b[1]*X**2+b[0]*X+c\n",
"plt.plot(z, z_mod, color='r', label=\"2nd Degree Fit\")\n",
"plt.title(\"Polynomial Regression\")\n",
"\n",
"plt.xlabel(\"Steps\")\n",
"plt.ylabel(\"Distance\")\n",
"\n",
"#Degree 10\n",
"poly_features10=PolynomialFeatures(degree=10, include_bias=False)\n",
"X_poly10=poly_features10.fit_transform(X)\n",
"\n",
"poly_fit10=lin_reg.fit(X_poly10,distance_list)\n",
"\n",
"y_plot=poly_fit10.predict(X_poly10)\n",
"plt.plot(X, y_plot, color='black', label=\"10th Degree Fit\")\n",
"\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"\n",
"#Decision Tree Regression\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"regr_1=DecisionTreeRegressor(max_depth=2)\n",
"regr_2=DecisionTreeRegressor(max_depth=5)\n",
"regr_3=DecisionTreeRegressor(max_depth=7)\n",
"regr_1.fit(X, distance_list)\n",
"regr_2.fit(X, distance_list)\n",
"regr_3.fit(X, distance_list)\n",
"\n",
"X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]\n",
"y_1 = regr_1.predict(X_test)\n",
"y_2 = regr_2.predict(X_test)\n",
"y_3=regr_3.predict(X_test)\n",
"\n",
"# Plot the results\n",
"plt.figure()\n",
"plt.scatter(X, distance_list, s=2.5, c=\"black\", label=\"data\")\n",
"plt.plot(X_test, y_1, color=\"red\",\n",
" label=\"max_depth=2\", linewidth=2)\n",
"plt.plot(X_test, y_2, color=\"green\", label=\"max_depth=5\", linewidth=2)\n",
"plt.plot(X_test, y_3, color=\"m\", label=\"max_depth=7\", linewidth=2)\n",
"\n",
"plt.xlabel(\"Data\")\n",
"plt.ylabel(\"Darget\")\n",
"plt.title(\"Decision Tree Regression\")\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Building a tree, regression\n",
"\n",
"There are mainly two steps\n",
"1. We split the predictor space (the set of possible values $x_1,x_2,\\dots, x_p$) into $J$ distinct and non-non-overlapping regions, $R_1,R_2,\\dots,R_J$. \n",
"\n",
"2. 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$.\n",
"\n",
"How do we construct the regions $R_1,\\dots,R_J$? In theory, the\n",
"regions could have any shape. However, we choose to divide the\n",
"predictor space into high-dimensional rectangles, or boxes, for\n",
"simplicity and for ease of interpretation of the resulting predictive\n",
"model. The goal is to find boxes $R_1,\\dots,R_J$ that minimize the\n",
"MSE, given by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\overline{y}_{R_j}$ is the mean response for the training observations \n",
"within box $j$. \n",
"\n",
"\n",
"Unfortunately, it is computationally infeasible to consider every\n",
"possible partition of the feature space into $J$ boxes. The common\n",
"strategy is to take a top-down approach\n",
"\n",
"The approach is top-down because it begins at the top of the tree (all\n",
"observations belong to a single region) and then successively splits\n",
"the predictor space; each split is indicated via two new branches\n",
"further down on the tree. It is greedy because at each step of the\n",
"tree-building process, the best split is made at that particular step,\n",
"rather than looking ahead and picking a split that will lead to a\n",
"better tree in some future step.\n",
"\n",
"\n",
"### Making a tree\n",
"\n",
"In order to implement the recursive binary splitting we start by selecting\n",
"the predictor $x_j$ and a cutpoint $s$ that splits the predictor space into two regions $R_1$ and $R_2$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\left\\{X\\vert x_j < s\\right\\},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\left\\{X\\vert x_j \\geq s\\right\\},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"so that we obtain the lowest MSE, that is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\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,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which we want to minimize by considering all predictors\n",
"$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n",
"each predictor. These values could be determined by randomly assigned\n",
"numbers or by starting at the midpoint and then proceed till we find\n",
"an optimal value.\n",
"\n",
"For any $j$ and $s$, we define the pair of half-planes where\n",
"$\\overline{y}_{R_1}$ is the mean response for the training\n",
"observations in $R_1(j,s)$, and $\\overline{y}_{R_2}$ is the mean\n",
"response for the training observations in $R_2(j,s)$.\n",
"\n",
"Finding the values of $j$ and $s$ that minimize the above equation can be\n",
"done quite quickly, especially when the number of features $p$ is not\n",
"too large.\n",
"\n",
"Next, we repeat the process, looking\n",
"for the best predictor and best cutpoint in order to split the data\n",
"further so as to minimize the MSE within each of the resulting\n",
"regions. However, this time, instead of splitting the entire predictor\n",
"space, we split one of the two previously identified regions. We now\n",
"have three regions. Again, we look to split one of these three regions\n",
"further, so as to minimize the MSE. The process continues until a\n",
"stopping criterion is reached; for instance, we may continue until no\n",
"region contains more than five observations.\n",
"\n",
"\n",
"The above procedure is rather straightforward, but leads often to\n",
"overfitting and unnecessarily large and complicated trees. The basic\n",
"idea is to grow a large tree $T_0$ and then prune it back in order to\n",
"obtain a subtree. A smaller tree with fewer splits (fewer regions) can\n",
"lead to smaller variance and better interpretation at the cost of a\n",
"little more bias.\n",
"\n",
"The so-called Cost complexity pruning algorithm gives us a\n",
"way to do just this. Rather than considering every possible subtree,\n",
"we consider a sequence of trees indexed by a nonnegative tuning\n",
"parameter $\\alpha$.\n",
"\n",
"Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py).\n",
"\n",
"\n",
"For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"is as small as possible. Here $\\overline{T}$ is \n",
"the number of terminal nodes of the tree $T$ , $R_m$ is the\n",
"rectangle (i.e. the subset of predictor space) corresponding to the $m$-th terminal node.\n",
"\n",
"The tuning parameter $\\alpha$ controls a trade-off between the subtrees\n",
"complexity and its fit to the training data. When $\\alpha = 0$, then the\n",
"subtree $T$ will simply equal $T_0$, \n",
"because then the above equation just measures the\n",
"training error. \n",
"However, as $\\alpha$ increases, there is a price to pay for\n",
"having a tree with many terminal nodes. The above equation will\n",
"tend to be minimized for a smaller subtree. \n",
"\n",
"\n",
"It turns out that as we increase $\\alpha$ from zero\n",
"branches get pruned from the tree in a nested and predictable fashion,\n",
"so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n",
"easy. We can select a value of $\\alpha$ using a validation set or using\n",
"cross-validation. We then return to the full data set and obtain the\n",
"subtree corresponding to $\\alpha$. \n",
"\n",
"\n",
"### Schematic Regression Procedure\n",
"\n",
"Building a Regression Tree\n",
"\n",
"1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n",
"\n",
"2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n",
"\n",
"3. 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: \n",
"\n",
" * repeat steps 1 and 2 on all but the $k$-th fold of the training data. \n",
"\n",
" * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\\alpha$.\n",
"\n",
" * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n",
"\n",
"\n",
"4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$. \n",
"\n",
"!eblock\n",
"\n",
"\n",
"\n",
"## A Classification Tree\n",
"\n",
"A classification tree is very similar to a regression tree, except\n",
"that it is used to predict a qualitative response rather than a\n",
"quantitative one. Recall that for a regression tree, the predicted\n",
"response for an observation is given by the mean response of the\n",
"training observations that belong to the same terminal node. In\n",
"contrast, for a classification tree, we predict that each observation\n",
"belongs to the most commonly occurring class of training observations\n",
"in the region to which it belongs. In interpreting the results of a\n",
"classification tree, we are often interested not only in the class\n",
"prediction corresponding to a particular terminal node region, but\n",
"also in the class proportions among the training observations that\n",
"fall into that region. \n",
"\n",
"\n",
"\n",
"The task of growing a\n",
"classification tree is quite similar to the task of growing a\n",
"regression tree. Just as in the regression setting, we use recursive\n",
"binary splitting to grow a classification tree. However, in the\n",
"classification setting, the MSE cannot be used as a criterion for making\n",
"the binary splits. A natural alternative to MSE is the **classification\n",
"error rate**. Since we plan to assign an observation in a given region\n",
"to the most commonly occurring error rate class of training\n",
"observations in that region, the classification error rate is simply\n",
"the fraction of the training observations in that region that do not\n",
"belong to the most common class. \n",
"\n",
"When building a classification tree, either the Gini index or the\n",
"entropy are typically used to evaluate the quality of a particular\n",
"split, since these two approaches are more sensitive to node purity\n",
"than is the classification error rate. \n",
"\n",
"\n",
"\n",
"If our targets are the outcome of a classification process that takes\n",
"for example $k=1,2,\\dots,K$ values, the only thing we need to think of\n",
"is to set up the splitting criteria for each node.\n",
"\n",
"We define a PDF $p_{mk}$ that represents the number of observations of\n",
"a class $k$ in a region $R_m$ with $N_m$ observations. We represent\n",
"this likelihood function in terms of the proportion $I(y_i=k)$ of\n",
"observations of this class in the region $R_m$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We let $p_{mk}$ represent the majority class of observations in region\n",
"$m$. The three most common ways of splitting a node are given by\n",
"\n",
"* Misclassification error"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Gini index $g$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Information entropy or just entropy $s$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visualizing the Tree, Classification"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import os\n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import confusion_matrix\n",
"from sklearn.tree import export_graphviz\n",
"\n",
"from IPython.display import Image \n",
"from pydot import graph_from_dot_data\n",
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"\n",
"cancer = load_breast_cancer()\n",
"X = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n",
"print(X)\n",
"y = pd.Categorical.from_codes(cancer.target, cancer.target_names)\n",
"y = pd.get_dummies(y)\n",
"print(y)\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n",
"tree_clf = DecisionTreeClassifier(max_depth=5)\n",
"tree_clf.fit(X_train, y_train)\n",
"\n",
"export_graphviz(\n",
" tree_clf,\n",
" out_file=\"DataFiles/cancer.dot\",\n",
" feature_names=cancer.feature_names,\n",
" class_names=cancer.target_names,\n",
" rounded=True,\n",
" filled=True\n",
")\n",
"cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
"os.system(cmd)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.datasets import make_moons\n",
"from sklearn.tree import export_graphviz\n",
"from pydot import graph_from_dot_data\n",
"import pandas as pd\n",
"import os\n",
"\n",
"np.random.seed(42)\n",
"X, y = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
"X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)\n",
"tree_clf = DecisionTreeClassifier(max_depth=5)\n",
"tree_clf.fit(X_train, y_train)\n",
"\n",
"export_graphviz(\n",
" tree_clf,\n",
" out_file=\"DataFiles/moons.dot\",\n",
" rounded=True,\n",
" filled=True\n",
")\n",
"cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'\n",
"os.system(cmd)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Other ways of visualizing the trees\n",
"\n",
"**Scikit-Learn** has also another way to visualize the trees which is very useful, here with the Iris data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.datasets import load_iris\n",
"from sklearn import tree\n",
"X, y = load_iris(return_X_y=True)\n",
"tree_clf = tree.DecisionTreeClassifier()\n",
"tree_clf = tree_clf.fit(X, y)\n",
"# and then plot the tree\n",
"tree.plot_tree(tree_clf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, the tree can also be exported in textual format with the function exporttext.\n",
"This method doesnt require the installation of external libraries and is more compact:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.datasets import load_iris\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.tree import export_text\n",
"iris = load_iris()\n",
"decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)\n",
"decision_tree = decision_tree.fit(iris.data, iris.target)\n",
"r = export_text(decision_tree, feature_names=iris['feature_names'])\n",
"print(r)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Algorithms for Setting up Decision Trees\n",
"\n",
"Two algorithms stand out in the set up of decision trees:\n",
"1. The CART (Classification And Regression Tree) algorithm for both classification and regression\n",
"\n",
"2. The ID3 algorithm based on the computation of the information gain for classification\n",
"\n",
"We discuss both algorithms with applications here. The popular library\n",
"**Scikit-Learn** uses the CART algorithm. For classification problems\n",
"you can use either the **gini** index or the **entropy** to split a tree\n",
"in two branches.\n",
"\n",
"### The CART algorithm for Classification\n",
"\n",
"For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$.\n",
"This could be for example a threshold set by a number below a certain circumference of a malign tumor.\n",
"\n",
"How do we find these two quantities?\n",
"We search for the pair $(k,t_k)$ that produces the purest subset using for example the **gini** factor $G$.\n",
"The cost function it tries to minimize is then"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n",
" is the number of instances in the left/right subset\n",
"\n",
"Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets\n",
"and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n",
"$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n",
"hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n",
"$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$.\n",
"\n",
"\n",
"### The CART algorithm for Regression\n",
"\n",
"The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the\n",
"training set in a way that minimizes say the **gini** or **entropy** impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here the MSE for a specific node is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"the mean value of all observations in a specific node.\n",
"\n",
"Without any regularization, the regression task for decision trees, \n",
"just like for classification tasks, is prone to overfitting.\n",
"\n",
"\n",
"\n",
"### Computing the Gini index\n",
"\n",
"The example we will look at is a classical one in many Machine\n",
"Learning applications. Based on various meteorological features, we\n",
"have several so-called attributes which decide whether we at the end\n",
"will do some outdoor activity like skiing, going for a bike ride etc\n",
"etc. The table here contains the feautures **outlook**, **temperature**,\n",
"**humidity** and **wind**. The target or output is whether we ride\n",
"(True=1) or whether we do something else that day (False=0). The\n",
"attributes for each feature are then sunny, overcast and rain for the\n",
"outlook, hot, cold and mild for temperature, high and normal for\n",
"humidity and weak and strong for wind.\n",
"\n",
"The table here summarizes the various attributes and\n",
"<table border=\"1\">\n",
"<thead>\n",
"<tr><th align=\"center\">Day</th> <th align=\"center\">Outlook </th> <th align=\"center\">Temperature</th> <th align=\"center\">Humidity</th> <th align=\"center\"> Wind </th> <th align=\"center\">Ride</th> </tr>\n",
"</thead>\n",
"<tbody>\n",
"<tr><td align=\"center\"> 1 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 0 </td> </tr>\n",
"<tr><td align=\"center\"> 2 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 3 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 4 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 5 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 6 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 0 </td> </tr>\n",
"<tr><td align=\"center\"> 7 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 8 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 0 </td> </tr>\n",
"<tr><td align=\"center\"> 9 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 10 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 11 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Mild </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 12 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 13 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Hot </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
"<tr><td align=\"center\"> 14 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 0 </td> </tr>\n",
"</tbody>\n",
"</table>\n",
"\n",
"### Simple Python Code to read in Data and perform Classification"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.tree import export_graphviz\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.compose import ColumnTransformer\n",
"from IPython.display import Image \n",
"from pydot import graph_from_dot_data\n",
"import os\n",
"\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"infile = open(data_path(\"rideclass.csv\"),'r')\n",
"\n",
"# Read the experimental data with Pandas\n",
"from IPython.display import display\n",
"ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n",
"ridedata = pd.DataFrame(ridedata)\n",
"\n",
"# Features and targets\n",
"X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n",
"y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n",
"\n",
"# Create the encoder.\n",
"encoder = OneHotEncoder(handle_unknown=\"ignore\")\n",
"# Assume for simplicity all features are categorical.\n",
"encoder.fit(X) \n",
"# Apply the encoder.\n",
"X = encoder.transform(X)\n",
"print(X)\n",
"# Then do a Classification tree\n",
"tree_clf = DecisionTreeClassifier(max_depth=2)\n",
"tree_clf.fit(X, y)\n",
"print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n",
"#transfer to a decision tree graph\n",
"export_graphviz(\n",
" tree_clf,\n",
" out_file=\"DataFiles/ride.dot\",\n",
" rounded=True,\n",
" filled=True\n",
")\n",
"cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
"os.system(cmd)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above functions (gini, entropy and misclassification error) are\n",
"important components of the so-called CART algorithm. We will discuss\n",
"this algorithm below after we have discussed the information gain\n",
"algorithm ID3.\n",
"\n",
"In the example here we have converted all our attributes into numerical values $0,1,2$ etc."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Split a dataset based on an attribute and an attribute value\n",
"def test_split(index, value, dataset):\n",
"\tleft, right = list(), list()\n",
"\tfor row in dataset:\n",
"\t\tif row[index] < value:\n",
"\t\t\tleft.append(row)\n",
"\t\telse:\n",
"\t\t\tright.append(row)\n",
"\treturn left, right\n",
" \n",
"# Calculate the Gini index for a split dataset\n",
"def gini_index(groups, classes):\n",
"\t# count all samples at split point\n",
"\tn_instances = float(sum([len(group) for group in groups]))\n",
"\t# sum weighted Gini index for each group\n",
"\tgini = 0.0\n",
"\tfor group in groups:\n",
"\t\tsize = float(len(group))\n",
"\t\t# avoid divide by zero\n",
"\t\tif size == 0:\n",
"\t\t\tcontinue\n",
"\t\tscore = 0.0\n",
"\t\t# score the group based on the score for each class\n",
"\t\tfor class_val in classes:\n",
"\t\t\tp = [row[-1] for row in group].count(class_val) / size\n",
"\t\t\tscore += p * p\n",
"\t\t# weight the group score by its relative size\n",
"\t\tgini += (1.0 - score) * (size / n_instances)\n",
"\treturn gini\n",
"\n",
"# Select the best split point for a dataset\n",
"def get_split(dataset):\n",
"\tclass_values = list(set(row[-1] for row in dataset))\n",
"\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n",
"\tfor index in range(len(dataset[0])-1):\n",
"\t\tfor row in dataset:\n",
"\t\t\tgroups = test_split(index, row[index], dataset)\n",
"\t\t\tgini = gini_index(groups, class_values)\n",
"\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n",
"\t\t\tif gini < b_score:\n",
"\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n",
"\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n",
" \n",
"dataset = [[0,0,0,0,0],\n",
" [0,0,0,1,1],\n",
" [1,0,0,0,1],\n",
" [2,1,0,0,1],\n",
" [2,2,1,0,1],\n",
" [2,2,1,1,0],\n",
" [1,2,1,1,1],\n",
" [0,1,0,0,0],\n",
" [0,2,1,0,1],\n",
" [2,1,1,0,1],\n",
" [0,1,1,1,1],\n",
" [1,1,0,1,1],\n",
" [1,0,1,0,1],\n",
" [2,1,0,1,0]]\n",
"\n",
"split = get_split(dataset)\n",
"print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Entropy and the ID3 algorithm\n",
"\n",
"The ID3 algorithm learns decision trees by constructing\n",
"them in a top down way, beginning with the question **which attribute should be tested at the root of the tree**?\n",
"\n",
"1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n",
"\n",
"2. The best attribute is selected and used as the test at the root node of the tree.\n",
"\n",
"3. A descendant of the root node is then created for each possible value of this attribute.\n",
"\n",
"4. Training examples are sorted to the appropriate descendant node.\n",
"\n",
"5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n",
"\n",
"6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n",
"\n",
"The ID3 algorithm selects which attribute to test at each node in the\n",
"tree.\n",
"\n",
"We would like to select the attribute that is most useful for classifying\n",
"examples.\n",
"\n",
"What is a good quantitative measure of the worth of an attribute?\n",
"\n",
"Information gain measures how well a given attribute separates the\n",
"training examples according to their target classification.\n",
"\n",
"The ID3 algorithm uses this information gain measure to select among the candidate\n",
"attributes at each step while growing the tree.\n",
"\n",
"\n",
"### Cancer Data again now with Decision Trees and other Methods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.svm import SVC\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"# Logistic Regression\n",
"logreg = LogisticRegression(solver='lbfgs')\n",
"logreg.fit(X_train, y_train)\n",
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
"# Support vector machine\n",
"svm = SVC(gamma='auto', C=100)\n",
"svm.fit(X_train, y_train)\n",
"print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n",
"# Decision Trees\n",
"deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n",
"deep_tree_clf.fit(X_train, y_train)\n",
"print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n",
"#now scale the data\n",
"from sklearn.preprocessing import StandardScaler\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"# Logistic Regression\n",
"logreg.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
"# Support Vector Machine\n",
"svm.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
"# Decision Trees\n",
"deep_tree_clf.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Another example, the moons again"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from __future__ import division, print_function, unicode_literals\n",
"\n",
"# Common imports\n",
"import numpy as np\n",
"import os\n",
"\n",
"# to make this notebook's output stable across runs\n",
"np.random.seed(42)\n",
"\n",
"# To plot pretty figures\n",
"import matplotlib\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"plt.rcParams['axes.labelsize'] = 14\n",
"plt.rcParams['xtick.labelsize'] = 12\n",
"plt.rcParams['ytick.labelsize'] = 12\n",
"\n",
"\n",
"from sklearn.svm import SVC\n",
"from sklearn import datasets\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.datasets import make_moons\n",
"from sklearn.tree import export_graphviz\n",
"\n",
"Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
"\n",
"deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n",
"deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n",
"deep_tree_clf1.fit(Xm, ym)\n",
"deep_tree_clf2.fit(Xm, ym)\n",
"\n",
"\n",
"def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n",
" x1s = np.linspace(axes[0], axes[1], 100)\n",
" x2s = np.linspace(axes[2], axes[3], 100)\n",
" x1, x2 = np.meshgrid(x1s, x2s)\n",
" X_new = np.c_[x1.ravel(), x2.ravel()]\n",
" y_pred = clf.predict(X_new).reshape(x1.shape)\n",
" custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
" plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
" if not iris:\n",
" custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
" plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
" if plot_training:\n",
" plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n",
" plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n",
" plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n",
" plt.axis(axes)\n",
" if iris:\n",
" plt.xlabel(\"Petal length\", fontsize=14)\n",
" plt.ylabel(\"Petal width\", fontsize=14)\n",
" else:\n",
" plt.xlabel(r\"$x_1$\", fontsize=18)\n",
" plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
" if legend:\n",
" plt.legend(loc=\"lower right\", fontsize=14)\n",
"plt.figure(figsize=(11, 4))\n",
"plt.subplot(121)\n",
"plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
"plt.title(\"No restrictions\", fontsize=16)\n",
"plt.subplot(122)\n",
"plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
"plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"np.random.seed(6)\n",
"Xs = np.random.rand(100, 2) - 0.5\n",
"ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n",
"\n",
"angle = np.pi/4\n",
"rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n",
"Xsr = Xs.dot(rotation_matrix)\n",
"\n",
"tree_clf_s = DecisionTreeClassifier(random_state=42)\n",
"tree_clf_s.fit(Xs, ys)\n",
"tree_clf_sr = DecisionTreeClassifier(random_state=42)\n",
"tree_clf_sr.fit(Xsr, ys)\n",
"\n",
"plt.figure(figsize=(11, 4))\n",
"plt.subplot(121)\n",
"plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
"plt.subplot(122)\n",
"plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Quadratic training set + noise\n",
"np.random.seed(42)\n",
"m = 200\n",
"X = np.random.rand(m, 1)\n",
"y = 4 * (X - 0.5) ** 2\n",
"y = y + np.random.randn(m, 1) / 10"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
"tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n",
"tree_reg.fit(X, y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
"tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n",
"tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n",
"tree_reg1.fit(X, y)\n",
"tree_reg2.fit(X, y)\n",
"\n",
"def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n",
" x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n",
" y_pred = tree_reg.predict(x1)\n",
" plt.axis(axes)\n",
" plt.xlabel(\"$x_1$\", fontsize=18)\n",
" if ylabel:\n",
" plt.ylabel(ylabel, fontsize=18, rotation=0)\n",
" plt.plot(X, y, \"b.\")\n",
" plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
"\n",
"plt.figure(figsize=(11, 4))\n",
"plt.subplot(121)\n",
"plot_regression_predictions(tree_reg1, X, y)\n",
"for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
" plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
"plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n",
"plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n",
"plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n",
"plt.legend(loc=\"upper center\", fontsize=18)\n",
"plt.title(\"max_depth=2\", fontsize=14)\n",
"\n",
"plt.subplot(122)\n",
"plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n",
"for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
" plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
"for split in (0.0458, 0.1298, 0.2873, 0.9040):\n",
" plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n",
"plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n",
"plt.title(\"max_depth=3\", fontsize=14)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"tree_reg1 = DecisionTreeRegressor(random_state=42)\n",
"tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n",
"tree_reg1.fit(X, y)\n",
"tree_reg2.fit(X, y)\n",
"\n",
"x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n",
"y_pred1 = tree_reg1.predict(x1)\n",
"y_pred2 = tree_reg2.predict(x1)\n",
"\n",
"plt.figure(figsize=(11, 4))\n",
"\n",
"plt.subplot(121)\n",
"plt.plot(X, y, \"b.\")\n",
"plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
"plt.axis([0, 1, -0.2, 1.1])\n",
"plt.xlabel(\"$x_1$\", fontsize=18)\n",
"plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n",
"plt.legend(loc=\"upper center\", fontsize=18)\n",
"plt.title(\"No restrictions\", fontsize=14)\n",
"\n",
"plt.subplot(122)\n",
"plt.plot(X, y, \"b.\")\n",
"plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
"plt.axis([0, 1, -0.2, 1.1])\n",
"plt.xlabel(\"$x_1$\", fontsize=18)\n",
"plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Pros and cons of trees, pros\n",
"\n",
"* 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)\n",
"\n",
"* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n",
"\n",
"* No feature normalization needed\n",
"\n",
"* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n",
"\n",
"* Can model nonlinear relationships\n",
"\n",
"* Can model interactions between the different descriptive features\n",
"\n",
"* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n",
"\n",
"### Disadvantages\n",
"\n",
"* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
"\n",
"* If continuous features are used the tree may become quite large and hence less interpretable\n",
"\n",
"* 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\n",
"\n",
"* 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\n",
"\n",
"* 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. \n",
"\n",
"* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n",
"\n",
"* 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\n",
"\n",
"However, by aggregating many decision trees, using methods like\n",
"bagging, random forests, and boosting, the predictive performance of\n",
"trees can be substantially improved."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}