{ "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\n", "\n", "Day Outlook Temperature Humidity Wind Ride \n", "\n", "\n", " 1 Sunny Hot High Weak 0 \n", " 2 Sunny Hot High Strong 1 \n", " 3 Overcast Hot High Weak 1 \n", " 4 Rain Mild High Weak 1 \n", " 5 Rain Cool Normal Weak 1 \n", " 6 Rain Cool Normal Strong 0 \n", " 7 Overcast Cool Normal Strong 1 \n", " 8 Sunny Mild High Weak 0 \n", " 9 Sunny Cool Normal Weak 1 \n", " 10 Rain Mild Normal Weak 1 \n", " 11 Sunny Mild Normal Strong 1 \n", " 12 Overcast Mild High Strong 1 \n", " 13 Overcast Hot Normal Weak 1 \n", " 14 Rain Mild High Strong 0 \n", "\n", "\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 }